我需要在临时文件中写入一些数据,并将该文件存储在目录 A 中。我使用 File.createTempFile 方法来执行此操作。但是,有一个线程定期轮询目录 A 以检查是否有临时文件需要处理。
// create a temporary file that will contain the data
newTmpFile = File.createTempFile("prefix", recoverFileExt, new File(
recoverDirectory));
// the file is set to non readable, so the recovery thread cannot
// access it
newTmpFile.setReadable(false);
//write data into the file
// the file is written, it is set to readable so the recovery thread
// can now access it
newTmpFile.setReadable(true);
问题是我不希望恢复线程在写操作完成之前访问该文件。所以,我使用这种机制:我创建文件,将其设置为不可读,写入它,然后将其设置为可读并关闭它。问题是文件创建后,文件仍然可读并且线程可以访问它。
所以,我想知道是否有可能在创建文件时将文件设置为不可读,或者您是否有其他解决方案。
谢谢
最佳答案
我的建议是首先为文件指定一个不同的名称(例如使用不同的前缀),然后在写入后重命名。
这样,恢复线程就可以区分部分写入和完全写入的文件,并仅处理后者。
关于java - 将文件设置为不可读,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8035459/