将文件设置为不可读

Mic*_*che 2 java file

我需要在临时文件中写入一些数据并将此文件存储在目录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);
Run Code Online (Sandbox Code Playgroud)

问题是我不希望恢复线程在写操作完成之前访问该文件.所以,我使用这个机制:我创建文件,将其设置为不可读,写入它然后将其设置为可读并关闭它.问题是,在文件创建之后,文件仍然可读,并且线程可以访问它.

所以,我想知道是否有可能在创建时将文件设置为不可读,或者是否有其他解决方案.

谢谢

NPE*_*NPE 5

我的建议是首先给文件一个不同的名称(例如使用不同的前缀),并在写完后重命名.

这样,恢复线程可以区分部分和完全写入的文件,只处理后者.