我实现了两种方法的copy
但是发现“方法1”copy出来的是没有换行的
“方法2”感觉又很麻烦
“方法2”里的换行是pw.println(s);实现的
可是s2在控制台打印出来的就是有换行的啊System.out.println(s2);
到底该怎么改良“方法1” 或者简化“方法2”?
哪种更常用呢?
我刚毕业 正在实习 希望大家多多指教o(∩_∩)o..import java.io.*;public class FileIoTest { public static void main(String[] args) throws IOException {
// 读取文件wed2.txt中的数据
FileReader fr = new FileReader("model.txt");
BufferedReader br = new BufferedReader(fr);
String s, s2 = new String();
while ((s = br.readLine()) != null)
s2 += s + "\n";
System.out.println(s2);
//写入到文件copy.txt 方法1
FileWriter fw = new FileWriter("copy1.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(s2);
bw.flush();
fw.close();
br.close();
//写入到文件copy.txt 方法2
StringReader sr = new StringReader(s2);
BufferedReader br2 = new BufferedReader(sr);
FileWriter fw2 = new FileWriter("copy2.txt");
BufferedWriter bw2 = new BufferedWriter(fw2);
PrintWriter pw = new PrintWriter(bw2);
while ((s = br2.readLine()) != null)
pw.println(s);
pw.close();
}
}我model.txt里写的内容是
this is the first line!
this is the second line!
this is the third line!
-----the End-------
但是发现“方法1”copy出来的是没有换行的
“方法2”感觉又很麻烦
“方法2”里的换行是pw.println(s);实现的
可是s2在控制台打印出来的就是有换行的啊System.out.println(s2);
到底该怎么改良“方法1” 或者简化“方法2”?
哪种更常用呢?
我刚毕业 正在实习 希望大家多多指教o(∩_∩)o..import java.io.*;public class FileIoTest { public static void main(String[] args) throws IOException {
// 读取文件wed2.txt中的数据
FileReader fr = new FileReader("model.txt");
BufferedReader br = new BufferedReader(fr);
String s, s2 = new String();
while ((s = br.readLine()) != null)
s2 += s + "\n";
System.out.println(s2);
//写入到文件copy.txt 方法1
FileWriter fw = new FileWriter("copy1.txt");
BufferedWriter bw = new BufferedWriter(fw);
bw.write(s2);
bw.flush();
fw.close();
br.close();
//写入到文件copy.txt 方法2
StringReader sr = new StringReader(s2);
BufferedReader br2 = new BufferedReader(sr);
FileWriter fw2 = new FileWriter("copy2.txt");
BufferedWriter bw2 = new BufferedWriter(fw2);
PrintWriter pw = new PrintWriter(bw2);
while ((s = br2.readLine()) != null)
pw.println(s);
pw.close();
}
}我model.txt里写的内容是
this is the first line!
this is the second line!
this is the third line!
-----the End-------
如果要复制一个文本文件
可以用字节流的拷贝(FileInputStream/FileOutputStream)
或者字符流的拷贝(FileReader/FileWriter)
那么哪种拷贝方法效率更高呢?
方法1 方法2哪种更常用呢? 如果要复制一个文本文件
可以用字节流的拷贝(FileInputStream/FileOutputStream)
或者字符流的拷贝(FileReader/FileWriter)
那么哪种拷贝方法效率更高呢?