Answer the question
In order to leave comments, you need to log in
How to correctly organize the deletion / renaming of a file in Java?
I am writing a desktop halloworld in JavaFX that can suck updates from the server and update itself to the current stable version.
I implemented it like this:
1. The main application (App.jar) checks if there are new versions, if there are, downloads a new version of itself (NewVerApp.jar) to its root folder and launches the console application Uppdater.jar, to which it passes its PID. (Assuming only one version of the app is running)
2. Uppdater.jar closes App.jar by its PID and tries to remove App.jar
3. Uppdater.jar renames NewVerApp.jar to App.jar
4. Uppdater.jar launches App.jar
5 .Uppdater.jar closes, update completed successfully.
The slippery point is that when Uppdater.jar closes App.jar, a subprocess is created that runs for a while:
/**
* Закрывает приложение по его PID
* @param pid
*/
public void killAppByPID(String pid){
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec("taskkill /F /PID " + pid);
} catch (IOException e) {
e.printStackTrace();
}
}
import java.io.File;
public class RenameFileThread implements Runnable{
private File srcFileNew, srcFileOld;
private Thread go;
// File srcFileNew = new File("NewVerApp.jar");
// File srcFileOld = new File("App.jar");
RenameFileThread(File srcFileNew, File srcFileOld){
this.srcFileNew = srcFileNew;
this.srcFileOld = srcFileOld;
go = new Thread(this);
go.start();
}
public void run(){
Thread th = Thread.currentThread();
while(go == th){
// если старый файл успешно переименован, называем новый именем старого файла
if (srcFileOld.delete()){
srcFileNew.renameTo(new File("App.jar"));
this.stop();
}
}
System.out.println("End of thread.");
}
public void stop(){ go = null; }
}
Runtime r = Runtime.getRuntime();
try {
Process p = r.exec("java -jar App.jar");
} catch (IOException e) {
e.printStackTrace();
}
Answer the question
In order to leave comments, you need to log in
What is Java Web Start :
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question