在不更改磁盘文件的情况下修改Java File属性



为了确保java.io.File在处理过程中不会被修改/删除,我想在

  • 用户无法访问
  • 但保存原始文件的信息(目录、名称…)

我需要原始文件的信息,因为有很多对文件信息的访问,如文件夹结构、文件名和文件扩展名。使用临时文件会破坏这些信息。

不幸的是,不可能只设置文件的名称/目录,因为这会重命名/移动文件。

替代方法:也可以同时处理这两个文件,从源文件中获取信息并从临时文件中读取内容,但这似乎不是最好的方法。

有更好的方法吗

致以最良好的问候Martin

听起来你想做的只是在读取文件时防止对文件进行任何修改。这通常是通过锁定文件来完成的,这样只有你的进程才能访问它。例如(使用java.nio中的FileLock)

try{
    File file = new File("randomfile.txt");
    FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    FileLock lock = channel.lock();//Obtain a lock on the file
    try{
        //Do your things
    }
    finally{
        lock.release();//Release the lock on the file
        channel.close();
    }
} 
catch (IOException e) {
   e.printStackTrace();
}

我建议您使用java.io.File.createTempFile(String,String,File),也可以使用java.io.File.deleteOnExit();用户必须可以访问该文件,否则用户将无法对其进行写入(QED)。也就是说,试试这样的东西-

try {
  File directory = new File("/tmp"); // or C:/temp ?
  File f = File.createTempFile("base-temp", ".tmp", directory); // create a new
              // temp file... with a prefix, suffix and in a tmp folder...
  f.deleteOnExit(); // Remove it when we exit (you can still explicitly delete when you're done). 
} catch (IOException e) {
  e.printStackTrace();
}

相关内容