(FileOutputStream类的应用)编写一个Java程序,在主方法main()中创建FileInputStream类和FileOutputStream类的实例,使它链接文件myInputfile.txt和myOutputfile.txt文件,实现把文件myInputfile.txt的内容复制到文件myOutputfile.txt中;
时间: 2024-03-01 18:53:34 浏览: 16
好的,以下是实现代码:
```java
import java.io.*;
public class CopyFile {
public static void main(String[] args) {
try {
FileInputStream input = new FileInputStream("myInputfile.txt");
FileOutputStream output = new FileOutputStream("myOutputfile.txt");
byte[] buffer = new byte[1024];
int length;
while ((length = input.read(buffer)) > 0) {
output.write(buffer, 0, length);
}
input.close();
output.close();
System.out.println("文件复制成功!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
```
解释一下代码:
1. 首先,在 try 语句块中创建了 FileInputStream 类和 FileOutputStream 类的实例,分别用于读取输入文件和写入输出文件。
2. 然后,定义了一个 byte 数组 buffer,用于存储从输入文件中读取出来的数据。
3. 接着,在 while 循环中,用 input.read(buffer) 方法读取输入文件中的数据,并把读取的数据写入到输出文件中,直到读取的数据长度为 0。
4. 最后,关闭输入输出流。
输出 "文件复制成功!" 表示程序执行成功。