Question

to make sure that a java.io.File is not modified/deleted during processing, I would like to create a temporary file in a different directory than the original file (e.g. System temp directory) that

  • cannot be accessed by the user
  • but holds the information (directory, name,...) of the original file

I need the original file's information, because there are lots of accesses on file-information, such as folder-structure, filename and file-extension. Working with the temporary file would destroy this information.

Unfortunately, it is not possible to just set a file's name/directory since this would rename/move the file.

Alternative approach: One could also work on both files, grabbing the information from the source-file and reading content from the temporary file but this does not seem like the optimal way to do this.

Is there a better approach to this?

Best regards Martin

Était-ce utile?

La solution

It sounds like what you want to do is just prevent any modifications to the file while you are reading from it. This is typically accomplished by locking the file, so that only your process can access it. As an example (using FileLock from java.nio)

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();
}

Autres conseils

I suggest you use java.io.File.createTempFile(String, String, File) and also use java.io.File.deleteOnExit(); the file must be accessible to the user - else the use cannot write to it (QED). That is, try something like this -

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();
}
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top