在学毕老师讲的ios时,他给我们留了个作业,就是用RandomAccessFile模拟一个多线程下载的程序。以下是我模拟的代码,也不知道这样模拟对不对?如果不对,正确的代码是什么。
- public class ClassTest {
- public static void main(String[] args)throws Exception {
- //这是源文件
- File f=new File("e:"+File.separator+"gjqt2_movie02.mp4");
- //这是复制的路径
- File k=new File("d:"+File.separator+"copy3.mp4");
- k.createNewFile();
- //每个线程用50M来分割
- long spilt=1024*1024*50;
- //求出线程数量
- int threadNum=(int)(f.length()/spilt);
- System.out.println(threadNum+1);
- //通过循环建立线程
- for(int x=0;x<=threadNum;x++)
- new Thread(new ThreadDownload(x,f,k)).start();
-
-
-
- }
- }
- class ThreadDownload implements Runnable{
-
- int account;
- int num=1;
- File fread=null;
- File fwrite=null;
-
- RandomAccessFile fr=null;
- RandomAccessFile fw=null;
- ThreadDownload(int account,File fread,File fwrite)
- {
- this.account=account;
- this.fread=fread;
- this.fwrite=fwrite;
- }
-
- public void run(){
-
- try{
-
- RandomAccessFile fr=new RandomAccessFile(fread,"r");
-
- RandomAccessFile fw=new RandomAccessFile(fwrite,"rw");
-
- fr.seek(1024*1024*50*account);
- fw.seek(1024*1024*50*account);
-
-
- byte[] buf=new byte[1024*1024];
- int length=0;
- while(num<=50&&(length=fr.read(buf))!=-1)
- {
- num++;
- fw.write(buf,0,length);
- buf=new byte[1024*1024];
- }
- }
- catch(Exception e)
- {
- throw new RuntimeException("下载失败");
- }
- finally
- {
- try{
- if(fr!=null)
- fr.close();
- }
- catch(Exception e)
- {
- throw new RuntimeException("读取关闭失败");
- }
- try{
- if(fw!=null)
- fw.close();
- }
- catch(Exception e)
- {
- throw new RuntimeException("写入关闭失败");
- }
-
- }
- }
- }
复制代码
复制文件和源文件大小一样但占用空间不一样,但是如果用windows自带的复制粘贴的话,文件大小和占用大小都一样,是不是我的代码有问题 |
|