user7291698
user7291698

Reputation: 1990

Interlacing BufferedWriter and PrintWriter

Is it safe to interlace BufferedWriter and PrintWriter in Java? Consider the following example:

private void writeToFile(File file, String text, Throwable throwable) throws Exception { // I use the "throws Exception" here for simplicity of the example
    // Write text
    BufferedWriter bufferedWriter = new BufferedWriter(new FileWriter(file));
    bufferedWriter.write(text);
    bufferedWriter.newLine();
    bufferedWriter.flush();

    // Write StackTrace
    PrintWriter printWriter = new PrintWriter(bufferedWriter);
    throwable.printStackTrace(printWriter);
    printWriter.close();
}

I know I could use the PrintWriter to write the text as well. But my questions are:

Note that the similar question here assumes that only the PrintWriter is accessed, and therefore doesn't answer my question.

Upvotes: 2

Views: 149

Answers (1)

m4gic
m4gic

Reputation: 1513

Is it safe to use a PrintWriter and the BufferedWriter this way?

As you can see in the documentation:

In general, a Writer sends its output immediately to the underlying character or byte stream. Unless prompt output is required, it is advisable to wrap a BufferedWriter around any Writer whose write() operations may be costly, such as FileWriters and OutputStreamWriters.

For example:

 PrintWriter out
   = new PrintWriter(new BufferedWriter(new FileWriter("foo.out")));

If it is safe, would it also be safe without the bufferedWriter.flush()?

Yes, it is safe. The flush() flushes the stream at the time you call it. IMHO, as a rule of thumb, without autoflush (and writing bigger amount to the stream) you have to call it before you close the stream.

Again, from the documentation:

public PrintWriter(OutputStream out)

Creates a new PrintWriter, without automatic line flushing, from an existing OutputStream. This convenience constructor creates the necessary intermediate OutputStreamWriter, which will convert characters into bytes using the default character encoding.

So, if you use this constructor you should call the flush() before close your stream, if you use the other public PrintWriter(Writer out, boolean autoFlush) and define true for autoflush, the call is unnecessary I think.

If it is safe, would it also be safe to use the BufferedWriter again, after I used the PrintWriter?

It would be safe, if you had define your FileWriter for append. Now you will overwrite your file at every call of your function. So I would use this constructor: FileWriter(File file, boolean append) and would specify true for append.

What is not that safe: your should use try-with-resources statement with autoflush or try-catch-finally and close (and maybe flush) your stream there in order to free your resources properly.

Upvotes: 2

Related Questions