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

I am writing a program that copies themselve on first run to a specific folder running on linux or windows.
On linux, it works fine, 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 another process is the program itself, what should I use to skip this error?

My lines of code:

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!

+13
source share
1 answer

Ok, I did not find the 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 copies the file and correctly deletes the original only when running linux.

I think that for this I need to call the class using the class loader.

+8
source

Source: https://habr.com/ru/post/1236842/


All Articles