简体   繁体   English

使用 Java 从 URL 下载 .jar 文件

[英]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.我已将更新系统集成到我的 Java 程序中,但缺少的一件事是使用 Java 从 URL 下载 jar 文件的方法。 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.我不知道该怎么做。

  1. Download the file using httpclient library in a specific folder.使用特定文件夹中的 httpclient 库下载文件。 Here is an example . 这是一个例子 Another example using Java's URLConnection class. 另一个使用 Java 的URLConnection类的示例
  2. Move/Delete/Backup the existing file.移动/删除/备份现有文件。
  3. Copy the downloaded file replacing the earlier file.复制下载的文件以替换之前的文件。

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您可以使用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您可以使用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...如果任何 Java 进程正在使用 Jar,您将无法更新它们...

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.通常,您希望更新程序成为不依赖于任何应用程序 jar 的单独程序。 This prevents the updater from locking the files it is trying to update.这可以防止更新程序锁定它正在尝试更新的文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM