I am trying to write to a file. I need to be able to "append" to the file rather than write over it. Also, I need it to be thread safe and efficient. The code I have currently is:
private void writeToFile(String data) {
File file = new File("/file.out");
try {
if (!file.exists()) {
//if file doesnt exist, create it
file.createNewFile();
}
PrintStream out = new PrintStream(new FileOutputStream(file, true));
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = new Date();
out.println(dateFormat.format(date) + " " + data);
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
It all works great. I just do not know if PrintStream is thread-safe or not. So, my question: Is writing to the same physical file from several instances of PrintStream safe? If so, does it use locking (reduces performance) or queueing? Do you know of any native java libraries that are thread-safe and use queueing? If not I have no problem writing my own. I am simply trying to see if there is anything native before I go write my own.