英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论