'Download .jar File From URL Using Java

I have integrated an update system into my Java program, and the one thing that is missing is a way to download a jar file from a URL using Java. How can one go about doing this? I would like the file to replace the existing one. I have no idea how to do this.



Solution 1:[1]

  1. Download the file using httpclient library in a specific folder. Here is an example. Another example using Java's URLConnection class.
  2. Move/Delete/Backup the existing file.
  3. Copy the downloaded file replacing the earlier file.

Solution 2:[2]

The question is vague, but if you don't mind getting your hands dirty...

Given a URL you can download the contents using Basic I/O

URL url = new URL("....");
InputStream is = null;
OutputStream os = null;
try {
    os = new FileOutputStream(new File("..."));
    is = url.openStream();
    // Read bytes...
} catch (IOException exp) {
    exp.printStackTrace();
} finally {
    try {
        is.close();
    } catch (Exception exp) {
    }
    try {
        os.close();
    } catch (Exception exp) {
    }
}

You can simply install these updates by using File#renameTo

The next problem you will have is installing the updates. The problem you might have is with locked files. If any Java process is using the Jar's, you won't be able to update them...

Now, this requires some clever juggling to make work, depending on your situation. Generally, you want to make the updater a separate program that does not rely on any of the application jars. This prevents the updater from locking the files it is trying to update.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Community
Solution 2 MadProgrammer