Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedReader then write to txt file?

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?

like image 366
Winter Leong Avatar asked Jul 12 '13 19:07

Winter Leong


2 Answers

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();
    }
}
like image 136
fge Avatar answered Sep 28 '22 00:09

fge


To directly answer your question:

you can, and you can also use BufferedWriter to do so.

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();
like image 37
user2577773 Avatar answered Sep 28 '22 02:09

user2577773