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:
- Is it safe to use a
PrintWriter
and theBufferedWriter
this way? - If it is safe, would it also be safe without the
bufferedWriter.flush()
? - If it is safe, would it also be safe to use the
BufferedWriter
again, after I used thePrintWriter
?
Note that the similar question here assumes that only the PrintWriter
is accessed, and therefore doesn't answer my question.