多线程下载和断点续传使用什么,java文件下载断点续传
爪哇岛文件的多线程断点续传大致原理,供大家参考,具体内容如下
谈到文件断点续传那么就离不开Java。io。randomacessfile http URL连接类
大致思路如下:
1、http网址连接去请求服务器获得文件的长度con.getContentLength()2,创建一个空的随机存取文件来接收,并且指定刚刚获取的长度设置长度3,开启英语字母表中第十四个字母个线程计算每个线程需要下载的长度4、获取之前先去看看下载的进度保存文件是否存在如果存在就从文件里获取已经下载的进度5、开始文件下载6、临时文件的删除资源的关闭
下面贴出完整代码
包演示;导入Java。io。缓冲阅读器;导入Java。io。文件;导入Java。io。文件输入流;导入Java。io。inputstream导入Java。io。inputstreamreader导入Java。io。随机存取文件;导入Java。网。httpurl连接;导入Java。网。网址;class MultiDownloaFile { public static final String path= http://192。168 .217 .1:8080/Android simpleserver/http。 pdf ;public static final int TOTAL _ THREAD _ COUNT=3;public static int运行线程计数=0;public static void main(String[]args){ try { long start=system。当前时间毫秒();URL url=新的网址(路径);http URL connection conn=(http URL connection)URL。打开连接();conn . setrequestmethod( GET );int code=conn . getresponsecode();if(code==200){ int length=conn . get contentlength();System.out.println(文件长度: 长度);//创建空文件保存其长度RandomAccessFile RAF=new RandomAccessFile(getDownloadFileName(path), rw );raf.setLength(长度);皇家空军。close();//解析每个线程自己需要多少空间下载int block size=长度/TOTAL _ THREAD _ COUNT;系统。出去。println(每个块大小: 块大小);运行线程数=TOTAL _ THREAD _ COUNTfor(int threadId=0;threadId TOTAL _ THREAD _ count threadId){ int start position=threadId * block size;int end position=(threadId 1)* block size-1;if(threadId==(TOTAL _ THREAD _ COUNT-1)){ end position=length-1;}系统。出去。println( thread : threadId 下载范围: 起始位置 ~ ~ 结束位置);//启动线程到
download new DownloadThread(threadId, startPosition, endPosition).start(); } } else { System.out.println(" connection error "); } } catch (Exception e) { e.printStackTrace(); } } /** * 从网络路径获取文件名 * * @param path 网络路径 * @return 文件名 */ private static String getDownloadFileName(String path) { return path.substring(path.lastIndexOf("/") + 1); } /** * 下载文件的线程 */ private static class DownloadThread extends Thread { /** * 线程id */ private int threadId; /** * 当前线程下载的起始位置 */ private int startPosition; /** * 当前线程下载的终止位置 */ private int endPosition; public DownloadThread(int threadId, int startPosition, int endPosition) { this.threadId = threadId; this.startPosition = startPosition; this.endPosition = endPosition; } @Override public void run() { System.out.println("thread:" + threadId + " begin working"); // lest thread download its self range data try { File finfo = new File(TOTAL_THREAD_COUNT + getDownloadFileName(path) + threadId + ".txt");// 断点续传 if (finfo.exists() && finfo.length() > 0) { System.out.println(" 断点续传开始"); FileInputStream fis = new FileInputStream(finfo); BufferedReader br = new BufferedReader(new InputStreamReader(fis)); String lastPosition = br.readLine(); // This thread download data before times; int intLastPosition = Integer.parseInt(lastPosition); startPosition = intLastPosition; fis.close(); } URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setRequestMethod("GET"); System.out.println("begin and end:" + threadId + " range of download: " + startPosition + "~~" + endPosition); conn.setRequestProperty("Range", "bytes=" + startPosition + "-" + endPosition); // Download Resource from server int code = conn.getResponseCode(); if (code == 206) { InputStream is = conn.getInputStream();// RandomAccessFile raf = new RandomAccessFile(getDownloadFileName(path), "rw"); RandomAccessFile raf = new RandomAccessFile(getDownloadFileName(path), "rw"); // vary important, position of begin to write raf.seek(startPosition); byte[] buffer = new byte[1024 * 100]; int len = -1; int total = 0; // downloaded data of current thread in this times; while ((len = is.read(buffer)) != -1) { raf.write(buffer, 0, len); // record position of current thread to downloading total += len; RandomAccessFile inforaf = new RandomAccessFile(TOTAL_THREAD_COUNT + getDownloadFileName(path) + threadId + ".txt", "rwd"); // save position of current thread inforaf.write(String.valueOf(startPosition + total).getBytes()); inforaf.close(); } is.close(); raf.close(); System.out.println("thread:" + threadId + " download complete..."); } else { System.out.println("request download failed."); } } catch (Exception e) { e.printStackTrace(); } finally { synchronized (MultiDownloaFile.class) { runningThreadCount--; if (runningThreadCount <= 0) { System.out.println(" all multi thread download complete. success!!!"); for (int i = 0; i < TOTAL_THREAD_COUNT; i++) { File finfo = new File(TOTAL_THREAD_COUNT + getDownloadFileName(path) + i + ".txt"); System.out.println(finfo.delete()); } } } } } }}以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持盛行IT。
郑重声明:本文由网友发布,不代表盛行IT的观点,版权归原作者所有,仅为传播更多信息之目的,如有侵权请联系,我们将第一时间修改或删除,多谢。