-2

I am writing to a text file in a while loop:

BufferedWriter writer = new BufferedWriter("...");
BufferedReader reader = new BufferedReader("...");

while((line = reader.readline()) != null){
    ....
    writer.write(line + "\n");
}

reader.close();
writer.close();

This code doesn't write the line to the file as soon as each line is processed. I want the line to be written into the file in each iteration. How to achieve that?

user697911
  • 10,043
  • 25
  • 95
  • 169

1 Answers1

1
  1. writer(line + "\n"); is not a method that exists. writer is the name of the BufferedWriter object. You need to add the method call to print your output with writer.println("...");

  2. You should surround your code in a try-catch clause when working with IO to prevent IOExceptions

  3. A simpler way to do this would be with a PrintWriter instead of a BufferedWriter.

faris
  • 692
  • 4
  • 18
  • In a while loop, BufferedWriter would be more efficient? Or not? – user697911 Sep 12 '18 at 00:50
  • The input should still be a BufferedReader but the output does nothing differently because of a while loop – faris Sep 12 '18 at 00:51
  • Isn't the case that the BufferedWriter accumulates data in multiple iterations and saves a lot of writing operations? So you mean in a typical while loop, BufferedWriter shouldn't be used? – user697911 Sep 12 '18 at 00:57
  • Read https://stackoverflow.com/questions/1747040/difference-between-java-io-printwriter-and-java-io-bufferedwriter – faris Sep 12 '18 at 01:00
  • According to the link, BuffereWriter is still more efficient but PrinterWriter provides more methods? BufferedWriter saves disk writing in a while loop? – user697911 Sep 12 '18 at 01:07
  • Unless you're seriously trying to save memory, in general I would go with PrintWriter – faris Sep 12 '18 at 01:12
  • My writer wraps in 'BufferedWriter(new OutputStreamWriter(new FileOutputStream(fileName)))', how is it compared to "PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));"? – user697911 Sep 12 '18 at 01:17
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/179866/discussion-between-faris-and-user697911). – faris Sep 12 '18 at 01:20
  • BufferedWriter is more efficient ... but you are negating the efficiency by requiring the output to be written to the file "promptly". – Stephen C Sep 12 '18 at 02:49
  • @StephenC I see. – user697911 Sep 12 '18 at 05:15