I have one method that opens a file and passes off to another function to write some data to it. That second method wants to use PrintWriter to write its data. However, I didn't want to require that everybody use PrintWriter to write to that stream.
Currently it looks something like this ( sanitized example... don't bother criticizing my choice of method or variable names )
public void exportRawDataIntoStream(OutputStream os) {
PrintWriter pr = new PrintWriter(os);
printFirstData(pr);
printSecondData(pr);
}
public void exportToFile(File file) {
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(file));
exportRawDataIntoStream(os);
doMoreWithTimeFile(os);
} finally {
if (os != null) {
try {
os.close();
} catch (Exception e ) {
e.printStackTrace();
}
}
}
}
This doesn't work, unless I put a 'pr.flush' at the end of exportRawDataIntoStream. I can't close the PrintWriter, because that closes the whole stream.
Is doing the flush legitimate and reliable? Is there some other approach I should use to mix Writers on the same stream, or should I just absolutely never do that?