我正在尝试写入文件。我需要能够“附加”到文件而不是覆盖它。另外,我需要它是线程安全和高效的。我目前的代码是:
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();
}
}
这一切都很好。我只是不知道 PrintStream 是否是线程安全的。所以,我的问题是:从多个 PrintStream 实例写入同一个物理文件是否安全?如果是这样,它是使用锁定(降低性能)还是排队?您知道任何线程安全并使用队列的本地 Java 库吗?如果没有,我自己写也没问题。在我自己写之前,我只是想看看是否有任何原生的东西。