St.Antario
St.Antario

Reputation: 27455

Printwriter to write into a file

Why can't I write a big amount of data via PrintWriter?

String result = acquireLengthyData();
PrintWriter out = new PrintWriter("D:/log.txt");
out.println(result);

where result.lenght() = 189718. But some data were missing in log.txt. Why? How can I write to the file correctly?

Upvotes: 0

Views: 216

Answers (2)

Subhrajyoti Majumder
Subhrajyoti Majumder

Reputation: 41230

You need to flush after write, it flushes the stream. PrintWriter#flush would do that.

Flushes the stream. If the stream has saved any characters from the various write() methods in a buffer, write them immediately to their intended destination.

PrintWriter#flush - Java doc

Code Snippet -

PrintWriter out = new PrintWriter("D:/log.txt");
out.println(result);
out.flush();
out.close();

And do not forget to close the writer after use.

Upvotes: 5

BatScream
BatScream

Reputation: 19700

Class PrintWriter

Unlike the PrintStream class, if automatic flushing is enabled it will be done only when one of the println, printf, or format methods is invoked, rather than whenever a newline character happens to be output. These methods use the platform's own notion of line separator rather than the newline character.

So you need to enable the automatic flush option while creating the Printwriter:

PrintWriter out = new PrintWriter(new FileWriter("D:/log.txt"),true);
out.println(result);
// finally{out.close();} with a null check, if required.

Note: Enabling auto flush will force the contents in the buffer to be written to the output stream, even if the buffer has not reached its content holding capacity.

Upvotes: 3

Related Questions