您好,登錄后才能下訂單哦!
這篇文章將為大家詳細講解有關在Java項目中如何利用多線程實現文件下載功能,文章內容質量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關知識有一定的了解。
具體內容如下
import java.io.File; import java.io.InputStream; import java.io.RandomAccessFile; import java.net.HttpURLConnection; import java.net.URL; public class MulThreadDownload { public static void main(String[] args) throws Exception { String path = "http://192.168.1.100:8080/Hello/Big.exe"; new MulThreadDownload().download(path, 3); } /** * 下載文件 * * @param path * 網絡文件路徑 * @param threadSize * 線程數 * @throws Exception */ private void download(String path, int threadSize) throws Exception { URL url = new URL(path); HttpURLConnection connection = (HttpURLConnection) url.openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); if (connection.getResponseCode() == 200) { int length = connection.getContentLength();// 獲取網絡文件長度 File file = new File(getFileName(path)); // 在本地生成一個長度與網絡文件相同的文件 RandomAccessFile accessFile = new RandomAccessFile(file, "rwd"); accessFile.setLength(length); accessFile.close(); // 計算每條線程負責下載的數據量 int block = length % threadSize == 0 ? length / threadSize : length / threadSize + 1; for (int threadId = 0; threadId < threadSize; threadId++) { new DownloadThread(threadId, block, url, file).start(); } } else { System.out.println("download fail"); } } private class DownloadThread extends Thread { private int threadId; private int block; private URL url; private File file; public DownloadThread(int threadId, int block, URL url, File file) { this.threadId = threadId; this.block = block; this.url = url; this.file = file; } @Override public void run() { int start = threadId * block; // 計算該線程從網絡文件什么位置開始下載 int end = (threadId + 1) * block - 1; // 計算下載到網絡文件什么位置結束 try { RandomAccessFile accessFile = new RandomAccessFile(file, "rwd"); accessFile.seek(start); //從start開始 HttpURLConnection connection = (HttpURLConnection) url .openConnection(); connection.setRequestMethod("GET"); connection.setConnectTimeout(5000); //設置獲取資源數據的范圍,從start到end connection.setRequestProperty("Range", "bytes=" + start + "-" + end); //注意多線程下載狀態碼是 206 不是200 if (connection.getResponseCode() == 206) { InputStream inputStream = connection.getInputStream(); byte[] buffer = new byte[1024]; int len = 0; while ((len = inputStream.read(buffer)) != -1) { accessFile.write(buffer, 0, len); } accessFile.close(); inputStream.close(); } System.out.println("第" + (threadId + 1) + "條線程已經下載完成"); } catch (Exception e) { e.printStackTrace(); } } } /** * 獲取文件名稱 * * @param path * 網絡文件路徑 * @return */ private String getFileName(String path) { return path.substring(path.lastIndexOf("/") + 1); } }
關于在Java項目中如何利用多線程實現文件下載功能就分享到這里了,希望以上內容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。