Java - How to replace a running jar file

Robin Withes :

I want my java application to be able to automatically keep itself up to date, i already made all the code to download the latest jar file and put it in the designated path but since my program has to be open to actually check if there are updates available and then update them it gives me this error:

Exception in thread "main" java.nio.file.FileSystemException: name.jar: The process cannot access the file because it is being used by another process

Now my question is not why i get this error since it is quite obvious why, the question is: how would i go about actually updating the .jar file succesfully since it has to be open to actually download the update? I'd rather not make another .jar to act like a standalone updater if there are other options.

Example of the code i'm using to test:

    URL url = new URL("<working url to the .jar file>");
    InputStream in = url.openStream();
    Files.copy(in, Paths.get("app.jar"), StandardCopyOption.REPLACE_EXISTING);
    in.close();
Zero :

First of all it is close to impossible to replace a running application, without restarting it, but there are techniques to transition fluidly. Here's a popular one (simplistic):

  • You launch application.exe, which checks version and finds that there's a new version.
  • application.exe launches updater.exe and closes itself (or waits, until updated version is downloaded and then closes itself.
  • updater.exe replaces the file and launches application.exe again.

So this part is a staple (replacing the core application), without some sort of hardcode memory hacks, to my knowledge.

If you don't need to update the actual core application and are willing to invest time into developing a dynamic library/asset management in your application, you can essentially unload a library or an asset, update it from application.exe and then reload it when it has finished updating, without needing to restart the application.

This might be the thing you are looking for, because if your application.exe is just a loader, and core logic of the application is 1 of the libraries, you can replace essentially any part of the application. You still have to "restart" that part of the application, but you can save and restore important data before restart and restore it after to make the transition somewhat fast and painless.

It's will most likely be time consuming to learn and implement.

Here's an answer with some insight into the second portion of the answer.

PS: I used ".exe" as a reference everywhere. Just imagine it's about jars, same principles apply.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=147132&siteId=1