public static final int threadCount =3; public static void main(String[] args) throws IOException { String path = "http://localhost:8080/oppo.mp4";//下载文件的路径,也可以是网上的路径 URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET");//Get请求 int code = conn.getResponseCode(); if(code == 200){ int length = conn.getContentLength();//文件的大小 RandomAccessFile raf = new RandomAccessFile("setup.mp4", "rwd"); /** "r" 以只读方式打开。调用结果对象的任何 write 方法都将导致抛出 IOException。 "rw" 打开以便读取和写入。如果该文件尚不存在,则尝试创建该文件。 "rws" 打开以便读取和写入,对于 "rw",还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备。 "rwd" 打开以便读取和写入,对于 "rw",还要求对文件内容的每个更新都同步写入到底层存储设备。 */ raf.setLength(length);//指定创建这个文件的大小 raf.close();//关闭流 //假设是三个线程 int blockSize = length / threadCount; for(int i = 1; i<=threadCount; i++){ int startIndex = (i-1)*blockSize; int endIndex = i*blockSize-1; if(i==threadCount){//当线程为最后一个线程,则末尾等于文件的大小 endIndex = length; } new DownloadThread(i, startIndex, endIndex, path).start();//开启线程 } } } public static class DownloadThread extends Thread{ private int threadId;//线程的Id private int startIndex;//下载的开始位置 private int endIndex;//下载的结束位置 private String path;//下载文件的路径 public DownloadThread(int threadId, int startIndex, int endIndex, String path) { super(); this.threadId = threadId; this.startIndex = startIndex; this.endIndex = endIndex; this.path = path; } @Override public void run() { try { URL url = new URL(path); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setConnectTimeout(5000); conn.setRequestMethod("GET"); conn.setRequestProperty("Range", "bytes="+startIndex+"-"+endIndex); int code = conn.getResponseCode(); System.out.println("code:"+code); //从服务器请求全部的资源成功返回 200 如果从服务器请求部分资源成功返回 206 if(code == 206){ InputStream is = conn.getInputStream();//已经设置了setRequestProperty //RandomAccessFile随机文件访问类,可以指定从某个位置开始下载 RandomAccessFile raf = new RandomAccessFile("setup.mp4", "rwd"); raf.seek(startIndex);//定位文件 int len = 0; byte[] buffer = new byte[1024]; while((len = is.read(buffer)) != -1){ raf.write(buffer,0,len); } is.close(); raf.close(); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
點(diǎn)擊查看更多內(nèi)容
為 TA 點(diǎn)贊
評(píng)論
評(píng)論
共同學(xué)習(xí),寫(xiě)下你的評(píng)論
評(píng)論加載中...
作者其他優(yōu)質(zhì)文章
正在加載中
感謝您的支持,我會(huì)繼續(xù)努力的~
掃碼打賞,你說(shuō)多少就多少
贊賞金額會(huì)直接到老師賬戶
支付方式
打開(kāi)微信掃一掃,即可進(jìn)行掃碼打賞哦
今天注冊(cè)有機(jī)會(huì)得
100積分直接送
付費(fèi)專(zhuān)欄免費(fèi)學(xué)
大額優(yōu)惠券免費(fèi)領(lǐng)