JAVA – 恢复/暂停 HTTPS 连接下载

huangapple go评论78阅读模式
英文:

JAVA - Resume/Pause https connection download

问题

以下是您要求的翻译内容:

我有这样的一个代码:

public void downloadZip(String URL, String fileName) {

    try {
        java.net.URL url = new URL(URL);
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();
        FileOutputStream out = new FileOutputStream(save + "/" + fileName);
        byte[] b = new byte[4096];
        int count;
        while ((count = in.read(b)) >= 0) {
            out.write(b, 0, count);
        }
        out.flush(); out.close(); in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

如何重写它以实现能够继续/停止加载?

英文:

I have a code like this

    public void downloadZip(String URL, String fileName) {

    try {
        java.net.URL url = new URL(URL);
        URLConnection conn = url.openConnection();
        InputStream in = conn.getInputStream();
        FileOutputStream out = new FileOutputStream(save + "/" + fileName);
        byte[] b = new byte[4096];
        int count;
        while ((count = in.read(b)) >= 0) {
            out.write(b, 0, count);
        }
        out.flush(); out.close(); in.close();

    } catch (IOException e) {
        e.printStackTrace();
    }
}

How can I rewrite it to be able to continue/stop loading?

答案1

得分: 1

你需要使用SwingUtilities来启用一个单独的线程。在GUI线程中,如果你想停止,可以设置一个标志。如果你想要恢复,可以重新打开URL,并使用InputStream的skip方法从上次离开的地方开始。要暂停和恢复,你可以使用信号。参见http://tutorials.jenkov.com/java-concurrency/thread-signaling.html。

你需要学习有关多线程的知识。

英文:

You need to use a separate thread using SwingUtilities. In the GUI thread you set a flag if you want to stop. If you want to resume, you can reopen the URL and use the skip method of the InputStream to start from where you left. To pause, resume you can use signals. See http://tutorials.jenkov.com/java-concurrency/thread-signaling.html.

You need to educate yourself about multi-threading.

huangapple
  • 本文由 发表于 2020年8月15日 18:04:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63424798.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定