使用多线程分片下载文件回顾

mac2024-03-22  26

package com.dhcc.thread; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.RandomAccessFile; public class ThreadDownload { String mubiao; String weizhi; int threadNum; public ThreadDownload(String mubiao, String weizhi, int threadNum) { this.mubiao = mubiao; this.weizhi = weizhi; this.threadNum = threadNum; } // 1.下载视频 // 2.new 多个线程 public void threadMul() throws IOException { int startIndex; int endIndex; int count; FileInputStream fis = new FileInputStream(new File(mubiao)); int total = fis.available(); count = total / threadNum; for (int i = 0; i < threadNum; i++) { startIndex = i * count; endIndex = (i + 1) * count - 1; new Thread(new Down(startIndex, endIndex, mubiao, weizhi)).start(); } } public static void main(String[] args) { ThreadDownload t = new ThreadDownload("E:/aaaaaaaa/85、搜狐邮箱.wmv", "E:/aaaaaaaa/bbbb.wmv", 3); try { t.threadMul(); } catch (IOException e) { e.printStackTrace(); } } } class Down extends Thread { int startIndex; int endIndex; String mubiao; String weizhi; public Down(int startIndex, int endIndex, String mubiao, String weizhi) { this.startIndex = startIndex; this.endIndex = endIndex; this.mubiao = mubiao; this.weizhi = weizhi; } @Override public void run() { try { downLoad(startIndex, endIndex); } catch (IOException e) { e.printStackTrace(); } } public void downLoad(int startIndex, int endIndex) throws IOException { File file = new File(mubiao); File file1 = new File(weizhi); RandomAccessFile fis = new RandomAccessFile(file, "r"); RandomAccessFile ran = new RandomAccessFile(file1, "rw"); byte[] bytes = new byte[20]; int len = 0; while (startIndex <= endIndex) { len = fis.read(bytes); ran.write(bytes, 0, len); startIndex += len; } fis.close(); ran.close(); } }

这些代码是我根据之前的思路,从新手写出来的,中间遇到一个很大的问题。

ran.write(bytes, 0, len);

这里报了IndexOutOfBoundException ,为什么呢?

首先说下 RandomAccessFile  这个类可以用来读写文件记录,write(byte[],起始位置,偏移量)    

这个类的最大好处是可以控制每次写入多少字节到文件里面。为什么需要控制呢?

因为最后一个读取的字节数肯定不能把缓冲读满,那么最后一次必然是新的字节和老的字节混在一起组成一个缓冲。

你把这个缓冲写到文件里面,字节肯定重复了。

 

使用这个方法注意的问题:

起始位置是固定不变的,用whie控制结束。我理解的是起始位置每次都要加上len,write方法每次都是移动到下一位,所以起始位置的值也会变化。但是不会,write根本不变,位置io会自动往后移动补充。不用管

 

 

最新回复(0)