我正在尝试写入文件。我需要能够“追加”到文件而不是覆盖它。此外,我需要它是线程安全和高效的。我当前拥有的代码是:
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库具有线程安全并使用排队的功能?如果没有,我没有问题编写自己的库。我只是想看看是否有原生的库。
PrintStream
的方法是synchronized
同步的。通过写缓冲区实现了排队。 - Marko Topolnik