我实现了两种方法的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.   

    顺便问一句
    如果要复制一个文本文件
    可以用字节流的拷贝(FileInputStream/FileOutputStream)
    或者字符流的拷贝(FileReader/FileWriter)
    那么哪种拷贝方法效率更高呢?
      

  2.   

    readLine是读到换行符为止(不包括换行符);方法1是把所有内容(没有换行)连接后打印,所以是连在一起打的;而方法2是读一行,打一行,println()本身就可以换行,所以是一行一行打的。
      

  3.   

    换行的问题我解决了 把\n前面加上\r 就行了我现在的问题是:
    方法1  方法2哪种更常用呢? 如果要复制一个文本文件 
    可以用字节流的拷贝(FileInputStream/FileOutputStream) 
    或者字符流的拷贝(FileReader/FileWriter) 
    那么哪种拷贝方法效率更高呢? 
      

  4.   

    方法2常用,因为如果文件内容过大,你全读到内存,不太好吧。个人感觉FileInputStream好点