Java使用IO流实现文件的拷贝
拷贝Copy
通过流FileInputStream + FileOutputStream完成文件的拷贝, 这个拷贝是可以拷贝任何类型的文件。(没有任何限制。)
package com.bjpowernode.javase.io;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
/**
* FileInputStream + FileOutputStream完成文件的拷贝.
* 这个拷贝是可以拷贝任何类型的文件。(没有任何限制。)
*/
public class Copy01 {
public static void main(String[] args) {
//创建文件字节输入流
//创建文件字节输出流
try (FileInputStream inputStream = new FileInputStream("D:\Java学习笔记\文本\c.txt");
FileOutputStream outputStream = new FileOutputStream("D:\Java学习笔记\文本\cc.txt");) {
//准备byte数组
byte[] bytes = new byte[1024];//一次最多读取1KB。
//一边读
int readCount = 0;
while((readCount = inputStream.read(bytes)) != -1){
outputStream.write(bytes,0,readCount);
}
//刷新
outputStream.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
拷贝(字符流)
使用FileReader和FileWriter完成文件的拷贝。 注意:这种拷贝只能拷贝普通文本文件。
package com.bjpowernode.javase.io;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
/**
* 使用FileReader和FileWriter完成文件的拷贝。
* 注意:这种拷贝只能拷贝普通文本文件。
*/
public class Copy02 {
public static void main(String[] args) {
try (FileReader reader = new FileReader("io/src/bb.txt");//ctrl+alt+t
FileWriter writer = new FileWriter("io/src/bb2.txt")) {
char[] chars = new char[512];
int readCount = 0;
while((readCount = reader.read(chars)) != -1){
writer.write(chars,0,readCount);
}
writer.flush();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
下一篇:
这些Java代码优化细节,你需要注意!
