package com.downloadthreads; import java.io.File; import java.io.RandomAccessFile; import java.util.Date; /* * 多线程下载示例 * * */ public class DownloadMain { private long startpoint; private int threadNum=5; private long filesize; private long currentPartSize; private File file=null; private File file1=null; /* *打开目标资源;创建目的文件,启用线程 */ public void download() throws Exception{ file1=new File("D:/test//test1.txt"); RandomAccessFile file=new RandomAccessFile("D:/test//test.txt","rw"); RandomAccessFile raf=new RandomAccessFile(file1,"rw"); //设置接收文件的大小 raf.setLength(file.length()); raf.close(); filesize=file.length(); currentPartSize=filesize/threadNum+1; // for(int i=0;i<threadNum;i++){ startpoint=i*currentPartSize; RandomAccessFile rafs=new RandomAccessFile(file1,"rw"); rafs.seek(startpoint); Thread t=new DownloadThread(startpoint,currentPartSize,rafs,file); t.start(); System.out.println(t.getName()); } } public static void main(String[] args) throws Exception { DownloadMain main=new DownloadMain(); System.out.println(new Date()); main.download(); System.out.println(new Date()); } }
package com.downloadthreads; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.RandomAccessFile; public class DownloadThread extends Thread{ private long startpoint; private long currentpartsize; private RandomAccessFile rafs; private RandomAccessFile file; public DownloadThread(long startpoint, long currentpartsize, RandomAccessFile rafs, RandomAccessFile file) { super(); this.startpoint = startpoint; this.currentpartsize = currentpartsize; this.rafs = rafs; this.file = file; } @Override public void run() { int hasread; int lenth=0; byte[] b=new byte[1024]; try { file.skipBytes((int)startpoint); while(lenth<currentpartsize&&(hasread=file.read(b))>0){ rafs.write(b); lenth+=hasread; } } catch (IOException e) { e.printStackTrace(); } } }