主要用到的
RandomAccessFile这个类的
seek()
![](https://i-blog.csdnimg.cn/blog_migrate/9d3664fa3f27ce4d3e2a647da625f8cd.png)
read()
![](https://i-blog.csdnimg.cn/blog_migrate/e1933551bff358d96e00a8dc615cd7e3.png)
1 import java.io.File; 2 3 import java.io.FileOutputStream; 4 import java.io.IOException; 5 import java.io.RandomAccessFile; 6 7 public class MultiThreading extends Thread { 8 private File file;// 要分割的文件; 9 private int size;// 每一块的大小 10 private int pos; // 位置的大小 11 private File file01; //分割的文件 12 13 public MultiThreading(File file, int size, int pos, File file01) { 14 super(); 15 this.file = file; 16 this.size = size; 17 this.pos = pos; 18 this.file01 = file01; 19 } 20 21 @Override 22 public void run() { 23 try { 24 segmentation(); 25 } catch (IOException e) { 26 // TODO Auto-generated catch block 27 e.printStackTrace(); 28 } 29 } 30 31 public void segmentation() throws IOException { 32 RandomAccessFile randomAccessFile = new RandomAccessFile(file, "r"); 33 randomAccessFile.seek((int) pos); //设置随机读取的位置 34 byte[] arr = new byte[size]; 35 int read = randomAccessFile.read(arr); //随机读取 36 FileOutputStream fileOutputStream = new FileOutputStream(file01); 37 fileOutputStream.write(arr, 0, read); 38 randomAccessFile.close(); 39 fileOutputStream.close(); 40 } 41 //测试方法如下 42 public static void main(String[] args) throws IOException { 43 int danwei = 1024*1024*10 ; 44 File file2 = new File("F:\\系统必备软件.zip"); 45 long length = file2.length(); 46 int unit = (int) ((length + danwei - 1) / danwei); 47 for (int i = 0; i < unit; i++) { 48 File createTempFile = new File("F:\\123\\" + (100000 + i + 1) + ".tmp"); 49 MultiThreading multiThreading = new MultiThreading(file2, danwei, i * danwei, createTempFile); 50 multiThreading.start(); 51 String name2 = multiThreading.getName(); 52 System.out.println("线程"+name2+"开始运行"); 53 } 54 55 } 56 }