如题,运用IO流的知识将给定路径下文件的内容复制到指定路径的另一个文件里。
思考步骤:
- 打开读写流
- 进行读写
- 关闭读写流
代码实现:
public class Demo {
public static void read()throws FileNotFoundException,IOException {
String path = "C:\\Users\\50579\\Desktop\\tt.txt"; //源文件路径
String path1 = "C:\\Users\\50579\\Desktop\\aa.txt"; //目的文件路径
FileInputStream fileInputStream = new FileInputStream(path); //用FileInputStream进行读
FileOutputStream fileOutputStream = new FileOutputStream(path1) ; //FileOutputStream写
//方法1
int byt = 0; //定义一个值,用来判断读的位置
while ((byt = fileInputStream.read()) != -1){ //用输入流读源文件,若byt等于-1表示读到文件内容结尾处,则退出循环
fileOutputStream.write(byt); //用输出流将读到的数据写入目的文件
}
//方法2
byte[] bytes = new byte[100];
while ((byt = fileInputStream.read(bytes))!= -1){
fileOutputStream.write(bytes,0, byt);
}
//错误方法3(会导致文件内容丢失一半)
while(fileInputStream.read()!= -1){
fileOutputStream.write(fileInputStream.read());
}
//错误方法4(文件大小受限:若文件太大,则太浪费CPU资源)
fileInputStream.read(bytes);
fileOutputStream.write(bytes);
fileInputStream.close(); //关闭输入流
fileOutputStream.close(); //关闭输出流
}
public static void main(String[] args) {
try {
read();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实现结果:
源文件的内容:(在读取之前目的文件为空或者不存在)
运行程序:(目的路径下通过字节输出流的write方法新建了一个文件aa.txt)
打开aa.txt,显示内容和tt.txt内容一样,实现了文件内容的复制功能