IMHO the accepted answer does not consider the fact that the intention is to write characters.
From the FileOutputStream
docs, you use FileOutputStream
when you want to print bytes.
FileOutputStream is meant for writing streams of raw bytes such as
image data. For writing streams of characters, consider using
FileWriter.
Besides, from the BufferedWriter
docs:
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.
Finally, the answer would be the following (as mentioned in this other StackOverFlow post):
PrintWriter out = null;
try {
out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)));
out.println("the text");
}catch (IOException e) {
System.err.println(e);
}finally{
if(out != null){
out.close();
}
}
Also, as of Java 7, you can use a try-with-resources statement. No
finally block is required for closing the declared resource(s) because
it is handled automatically, and is also less verbose:
try(PrintWriter out = new PrintWriter(new BufferedWriter(new FileWriter("writePath", true)))) {
out.println("the text");
}catch (IOException e) {
System.err.println(e);
}