一、需求:实现一文件复制到另一目录
二、思路:
1、需要读取的数据源 2、将读取到的数据写入到目的地 3、操作文本数据,就是使用字符流
三、代码演示:
(一)、效率低
//1、读取一个已有的文件。使用字符读取流
FileReader fr = new FileReader("demo.txt");
//2、创建一个目的地,用于存储读到的数据
FileWriter fw = new FileWriter("Writer.txt");
//3、频繁的读写操作
int ch=0;
while ((ch=fr.read())!=-1){
fw.write(ch);
}
//4、关闭流资源
fw.close();
fr.close();
(二)、效率高、规范
public static void main(String[] args) throws IOException{
FileReader fr =null;
FileWriter fw =null;
try {
fr = new FileReader("demo.txt");
fw = new FileWriter("CopyTest.txt");
char[] ch = new char[BUFFER_SIZE];
int len = 0;
while ((len = fr.read(ch)) !=-1){
fw.write(ch,0,len);
}
} catch (Exception e) {
throw new RuntimeException("读写失败....");
} finally {
if (fw !=null){
fw.close();
}
if (fr !=null){
fr.close();
}
}
}