I prefer:
boolean append = true;
boolean autoFlush = true;
String charset = "UTF-8";
String filePath = "C:/foo.txt";
File file = new File(filePath);
if(!file.getParentFile().exists()) file.getParentFile().mkdirs();
FileOutputStream fos = new FileOutputStream(file, append);
OutputStreamWriter osw = new OutputStreamWriter(fos, charset);
BufferedWriter bw = new BufferedWriter(osw);
PrintWriter pw = new PrintWriter(bw, autoFlush);
pw.write("Some File Contents");
which gives you:
- Decide whether to append to the text file or overwrite it.
- Decide whether to make it auto-flush or not.
- Specify the charset.
- Make it buffered, which improves the streaming performance.
- Convenient methods (such as
println()
and its overloaded ones).