BufferedReader then write to txt file?

Winter Leong picture Winter Leong · Jul 12, 2013 · Viewed 35.2k times · Source

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?

Answer

fge picture fge · Jul 12, 2013

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