HttpDownloader.java
package com.buyishi; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; public class HttpDownloader { private final String url, destFilename; public HttpDownloader(String url, String destFilename) { this.url = url; this.destFilename = destFilename; } public void download(Callback callback) { try (FileOutputStream fos = new FileOutputStream(destFilename)) { URLConnection connection = new URL(url).openConnection(); long fileSize = connection.getContentLengthLong(); InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[10 * 1024 * 1024]; int numberOfBytesRead; long totalNumberOfBytesRead = 0; while ((numberOfBytesRead = inputStream.read(buffer)) != - 1) { fos.write(buffer, 0, numberOfBytesRead); totalNumberOfBytesRead += numberOfBytesRead; callback.onProgress(totalNumberOfBytesRead * 100 / fileSize); } callback.onFinish(); } catch (IOException ex) { callback.onError(ex); } } public interface Callback { void onProgress(long progress); void onFinish(); void onError(IOException ex); } }
OkHttpDownloader.java //基于OkHttp
package com.buyishi; import java.io.BufferedInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import okhttp3.OkHttpClient; import okhttp3.Request; import okhttp3.ResponseBody; public class OkHttpDownloader { private final String url, destFilename; private static final Logger LOGGER = Logger.getLogger(OkHttpDownloader.class.getName()); public OkHttpDownloader(String url, String destFilename) { this.url = url; this.destFilename = destFilename; } public void download(Callback callback) { BufferedInputStream input = null; try (FileOutputStream fos = new FileOutputStream(destFilename)) { Request request = new Request.Builder().url(url).build(); ResponseBody responseBody = new OkHttpClient().newCall(request).execute().body(); long fileSize = responseBody.contentLength(); input = new BufferedInputStream(responseBody.byteStream()); byte[] buffer = new byte[10 * 1024 * 1024]; int numberOfBytesRead; long totalNumberOfBytesRead = 0; while ((numberOfBytesRead = input.read(buffer)) != - 1) { fos.write(buffer, 0, numberOfBytesRead); totalNumberOfBytesRead += numberOfBytesRead; callback.onProgress(totalNumberOfBytesRead * 100 / fileSize); } callback.onFinish(); } catch (IOException ex) { callback.onError(ex); } finally { if (input != null) { try { input.close(); } catch (IOException ex) { LOGGER.log(Level.SEVERE, null, ex); } } } } public interface Callback { void onProgress(long progress); void onFinish(); void onError(IOException ex); } }
MainFrame.java //对两个工具类的测试
package com.buyishi; import java.awt.GridLayout; import java.awt.event.MouseAdapter; import java.awt.event.MouseEvent; import java.io.IOException; import java.util.logging.Level; import java.util.logging.Logger; import javax.swing.JButton; import javax.swing.JFrame; public class MainFrame extends JFrame { private final JButton test1Button, test2Button; private static final Logger LOGGER = Logger.getLogger(MainFrame.class.getName()); private MainFrame() { super("Download Test"); super.setSize(300, 200); super.setLocationRelativeTo(null); super.setDefaultCloseOperation(EXIT_ON_CLOSE); super.setLayout(new GridLayout(2, 1)); test1Button = new JButton("测试1"); test2Button = new JButton("测试2"); super.add(test1Button); super.add(test2Button); test1Button.addMouseListener(new MouseAdapter() { private boolean downloadStarted; @Override public void mouseClicked(MouseEvent e) { if (!downloadStarted) { downloadStarted = true; new Thread() { @Override public void run() { String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE"; // String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe"; new HttpDownloader(url, "C:/Users/BuYishi/Desktop/file1").download(new HttpDownloader.Callback() { @Override public void onProgress(long progress) { LOGGER.log(Level.INFO, "{0}", progress); test1Button.setText("Downloading..." + progress + "%"); } @Override public void onFinish() { LOGGER.log(Level.INFO, "Download finished"); test1Button.setText("Downloaded"); } @Override public void onError(IOException ex) { LOGGER.log(Level.SEVERE, null, ex); downloadStarted = false; } }); } }.start(); } } }); test2Button.addMouseListener(new MouseAdapter() { private boolean downloadStarted; @Override public void mouseClicked(MouseEvent e) { if (!downloadStarted) { downloadStarted = true; new Thread() { @Override public void run() { String url = "http://download.microsoft.com/download/A/C/9/AC924EA1-9F39-4DFD-99DF-2C1DEB922174/EIE11/WOL/EIE11_ZH-CN_WOL_WIN764.EXE"; // String url = "https://dl.360safe.com/drvmgr/360DrvMgrInstaller_net.exe"; new OkHttpDownloader(url, "C:/Users/BuYishi/Desktop/file2").download(new OkHttpDownloader.Callback() { @Override public void onProgress(long progress) { test2Button.setText("Downloading..." + progress + "%"); } @Override public void onFinish() { test2Button.setText("Downloaded"); } @Override public void onError(IOException ex) { LOGGER.log(Level.SEVERE, null, ex); downloadStarted = false; } }); } }.start(); } } }); } public static void main(String[] args) { MainFrame frame = new MainFrame(); frame.setVisible(true); } }
原文地址:https://www.cnblogs.com/buyishi/p/9379930.html
时间: 2024-10-14 04:24:20