Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将文件设置为不可读取_Java_File - Fatal编程技术网

Java 将文件设置为不可读取

Java 将文件设置为不可读取,java,file,Java,File,我需要在一个临时文件中写入一些数据,并将该文件存储在目录a中。我使用file.createTempFile方法来执行此操作。但是,有一个线程会定期轮询目录a,以检查是否有要处理的临时文件 // create a temporary file that will contain the data newTmpFile = File.createTempFile("prefix", recoverFileExt, new File( recoverDirectory)

我需要在一个临时文件中写入一些数据,并将该文件存储在目录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);
问题是我不希望恢复线程在写操作完成之前访问该文件。因此,我使用这种机制:创建文件,将其设置为不可读,写入文件,然后将其设置为可读并关闭。问题是,在文件创建之后,文件仍然是可读的,线程可以访问它

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


谢谢

我的建议是,首先为文件指定一个不同的名称(例如,使用不同的前缀),然后在写入文件后对其重命名


通过这种方式,恢复线程可以区分部分写入的文件和完全写入的文件,并且只处理后者。

IMHO这不是解决问题的方法。使用信号量/互斥来控制线程同步。尝试使用文件同步线程是一个坏习惯,以后会导致更多错误

创建文件索引

您不应该以这种方式将文件系统用作锁定机制。使用不同文件名的Aix解决方案可以工作,但并不理想

更好的解决方案是在内存中加载一个文件索引,使两个线程都可以访问。无论何时创建要处理的文件,一旦文件完成并准备好进行处理,请将其添加到索引中。然后恢复线程将只访问索引中给定的要处理的文件

// 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);

此索引实际上是恢复线程的工作队列。

我将通过创建一个线程将忽略的特殊名称的文件来绕过它。然后您首先重命名它,然后将其更改为可读。因此,您将进行两项检查—文件是否不可读取以及文件是否具有特殊名称。

如果线程处于同一进程中,您可以保留一个计数器,用于控制安全写入的数据量。这样,您几乎可以在写入恢复日志后立即对其进行处理。

请注意,如果文件位于同一文件系统中,您还可以在目录之间快速重命名文件。(这不是NFS所推荐的,但NFS并不真正追求“数据完整性”。)我接受其功能的答案。但是,我知道使用文件名进行同步不是一个好的做法。