使用 Java 从 URL 下载 .jar 文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18754266/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 10:45:19  来源:igfitidea点击:

Download .jar File From URL Using Java

javajardownloadexecutableexecutable-jar

提问by user2770917

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.

我已将更新系统集成到我的 Java 程序中,但缺少的一件事是使用 Java 从 URL 下载 jar 文件的方法。一个人怎么能这样做呢?我希望该文件替换现有文件。我不知道该怎么做。

回答by Santosh

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

回答by MadProgrammer

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

这个问题很模糊,但如果你不介意弄脏你的手......

Given a URLyou can download the contents using Basic I/O

鉴于URL您可以使用基本 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. This prevents the updater from locking the files it is trying to update.

现在,这需要一些巧妙的技巧才能发挥作用,具体取决于您的情况。通常,您希望更新程序成为不依赖于任何应用程序 jar 的单独程序。这可以防止更新程序锁定它正在尝试更新的文件。