----------------------
ASP.Net+Unity开发、
.Net培训、期待与您交流! ----------------------
通过这个小练习来加强对FileReader和FileWriter的基本认识,并且要有完整的异常处理
/*复制文件到指定目录
* 1.在指定目录创建一个文件,用于存储被copy文件的数据
* 2.定义读取流和文件关联
* 3.通过不断地读写完成数据存储
* 4.关闭资源
* */
package iotest;
import java.io.*;
public class CopyText {
public static void main(String[] args){
copy_1();
}
public static void copy_1(){
FileReader fr = null;
FileWriter fw = null;
try{
fr = new FileReader("./src/test/FileReaderDemo.java");
fw = new FileWriter("copy.txt",true);
char[] buf = new char[1024];
int len = 0;
while((len = fr.read(buf))!= -1){
fw.write(buf,0,len);
//fw.flush();
}
}catch (IOException e) {
throw new RuntimeException("读写失败");
}finally{ //一定要对流进行非空判断
if(fw != null)
try{
fw.close();
}catch(IOException e){
System.out.println(e.toString());
}
if(fr != null)
try{
fr.close();
}catch(IOException e){
System.out.println(e.toString());
}
}
}
}
----------------------
ASP.Net+Unity开发、
.Net培训、期待与您交流! ----------------------