BufferedReader然后写入到txt文件? [英] BufferedReader then write to txt file?

查看:314
本文介绍了BufferedReader然后写入到txt文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能使用BufferedReader从文本文件中读取数据,然后当缓冲读取器正在读取数据时,同时它还使用PrintWriter将读取的行存储到另一个txt文件中?


如果您使用Java 7,并且想要将一个文件直接复制到另一个文件中,就像下面这样简单:

 最终路径src = Paths.get(...); 
最终路径dst = Paths.get(...);
Files.copy(src,dst);

如果您想逐行阅读并重新写入,请抓取 src dst 与上面相同,然后执行:

  final BufferedReader reader; 
最终的BufferedWriter作家;
字符串行;

try(
reader = Files.newBufferedReader(src,StandardCharsets.UTF_8);
writer = Files.newBufferedWriter(dst,StandardCharsets.UTF_8);
){ ((line = reader.readLine())!= null){
doSomethingWith(line);
writer.write(line);
//必须这样做:.readLine()将会有行结束符
writer.newLine();
}
}


Is it possible to use BufferedReader to read from a text file, and then while buffered reader is reading, at the same time it also storing the lines it read to another txt file using PrintWriter?

解决方案

If you use Java 7 and want to copy one file directly into another, it is as simple as:

final Path src = Paths.get(...);
final Path dst = Paths.get(...);
Files.copy(src, dst);

If you want to read line by line and write again, grab src and dst the same way as above, then do:

final BufferedReader reader;
final BufferedWriter writer;
String line;

try (
    reader = Files.newBufferedReader(src, StandardCharsets.UTF_8);
    writer = Files.newBufferedWriter(dst, StandardCharsets.UTF_8);
) {
    while ((line = reader.readLine()) != null) {
        doSomethingWith(line);
        writer.write(line);
        // must do this: .readLine() will have stripped line endings
        writer.newLine();
    }
}

这篇关于BufferedReader然后写入到txt文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆