@Test
public void copy() {
String str1 = new String("HelloWorld.txt");
String str2 = new String("HelloWorld2.txt");
File file1 = new File(str1);
File file2 = new File(str2);
FileReader fr = null;
FileWriter fw = null;
BufferedReader br = null;
BufferedWriter bw = null;
try {
fr = new FileReader(file1);
fw = new FileWriter(file2);
br = new BufferedReader(fr);
bw = new BufferedWriter(fw);
//此方法可以将读取到的数据换行
/*char[] c = new char[1024];
int len;
while((len = br.read(c)) != -1){
String str = new String(c,0,len);
bw.write(str);
bw.flush();
}*/
//此方法不能将读取到的数据换行
String str ;
while((str = br.readLine()) != null){
bw.write(str);
System.out.println(str);
bw.flush();
}
} catch (Exception e) {
// TODO: handle exception
}finally{
if(bw != null){
try {
bw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(br != null){
try {
br.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fw != null){
try {
fw.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if(fr != null){
try {
fr.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
网友评论