Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process

Tags:

java

windows

I'm writing a program that copy themselve at first execution to a specific folder, working in linux or windows.
In linux it works perfectly but when I try to do the same on windows i get the following error:

java.nio.file.FileSystemException: The process cannot access the file because it is being used by another process (in sun.nio.fs.WindowsException)

So, the other process is the program itself, what should I use to skip this error?

My code lines are:

public void installProgram (){
    System.out.println("Doing Install...");
    File fileToBeInstalled = new File(MyClass.class.getProtectionDomain().getCodeSource().getLocation().toURI().getPath());

     try {
        Files.move(fileToBeInstalled.toPath(), installPathFile.toPath(), REPLACE_EXISTING);
     } catch (IOException ex) {
        MainClass.getMainClass(InstallerLinux.class.getName()).log(Level.SEVERE, null, ex);

    }
} 

Thanks!

like image 391
selan Avatar asked Nov 25 '15 19:11

selan


People also ask

How do you delete a file that is used by another process in Java?

Method available in every Java versionFile filePath = new File( "SomeFileToDelete. txt" ); boolean success = filePath. delete();

How do you delete a file in Java?

In Java, we can delete a file by using the File. delete() method of File class. The delete() method deletes the file or directory denoted by the abstract pathname. If the pathname is a directory, that directory must be empty to delete.


1 Answers

Ok, I don't found a perfect solution but something...

try {
        //Files.move(fileToBeInstalled.toPath(), installPathFile.toPath(), REPLACE_EXISTING);
        Files.copy(fileToBeInstalled.toPath(), installPathFile.toPath(), REPLACE_EXISTING);
        fileToBeInstalled.delete();
} catch (IOException ex) {
    MainClass.getMainClass(InstallerLinux.class.getName()).log(Level.SEVERE, null, ex);

}

This copy correctly the file and erases correctly the original only on linux execution.

I think for do that I need to invoke the class using a class loader..

like image 112
selan Avatar answered Sep 18 '22 12:09

selan