简体   繁体   English

然后BufferedReader写入txt文件?

[英]BufferedReader then write to txt file?

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

If you use Java 7 and want to copy one file directly into another, it is as simple as: 如果您使用Java 7并希望将一个文件直接复制到另一个文件中,则它非常简单:

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: 如果你想逐行阅读并再次写,请以与上面相同的方式获取srcdst ,然后执行:

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();
    }
}

To directly answer your question: 直接回答你的问题:

you can, and you can also use BufferedWriter to do so. 你可以,你也可以使用BufferedWriter这样做。

BufferedReader br = new BufferedReader(new FileReader(new File("Filepath")));
BufferedWriter bw = new BufferedWriter(new FileWriter(new File("Filepath")));
String l;
while((l=br.readLine())!=null){

    ... do stuff ...

    bw.write("what you did");

}

bw.close();

Yes. 是。 Open the BufferedReader , and then create a PrintWriter . 打开BufferedReader ,然后创建PrintWriter You can read from the stream as you write to the writer. 您可以在写入编写器时从流中读取。

If you just need to copy without inspecting the data, then it's a one liner: 如果您只需要在不检查数据的情况下进行复制,那么它就是一个内容:
IOUtils.copy(reader, printWriter); IOUtils.copy(reader,printWriter);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM