一个关于文件拷贝的问题 java

huahuamay 2007-12-28 11:28:54
我实现了两种方法的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-------
...全文
171 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
huahuamay 2007-12-28
  • 打赏
  • 举报
回复
顺便问一句
如果要复制一个文本文件
可以用字节流的拷贝(FileInputStream/FileOutputStream)
或者字符流的拷贝(FileReader/FileWriter)
那么哪种拷贝方法效率更高呢?
Nuage 2007-12-28
  • 打赏
  • 举报
回复
大文件一般都要用buffer的吧.
不懂编程 2007-12-28
  • 打赏
  • 举报
回复
方法2常用,因为如果文件内容过大,你全读到内存,不太好吧。

个人感觉FileInputStream好点
huahuamay 2007-12-28
  • 打赏
  • 举报
回复
换行的问题我解决了 把\n前面加上\r 就行了

我现在的问题是:
方法1 方法2哪种更常用呢?

如果要复制一个文本文件
可以用字节流的拷贝(FileInputStream/FileOutputStream)
或者字符流的拷贝(FileReader/FileWriter)
那么哪种拷贝方法效率更高呢?
不懂编程 2007-12-28
  • 打赏
  • 举报
回复
readLine是读到换行符为止(不包括换行符);方法1是把所有内容(没有换行)连接后打印,所以是连在一起打的;而方法2是读一行,打一行,println()本身就可以换行,所以是一行一行打的。

62,623

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧