rt

解决方案 »

  1.   

    import java.io.File;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.RandomAccessFile;
    import java.net.HttpURLConnection;
    import java.net.MalformedURLException;
    import java.net.URL;
    public class ThreadDownload implements Runnable {
    private URL url;
    private File file;
    private int offset;
    private int len;
    private String net;
    private InputStream in;
    private RandomAccessFile random;
    private HttpURLConnection httpConnection;
    @Override
    public void run() {
    StartDownload();
    }
    public ThreadDownload(String net,File file,int offset,int len)
    {
    this.net=net;
    this.file=file;
    this.offset=offset;
    this.len=len;
    }
    public void StartDownload() 
    {
    long start = System.currentTimeMillis();
    int byteread=0;
    System.out.println("begin to download the file");
    System.out.println("the offset is "+offset);
    byte[] b=new byte[1024];
    try {
    url=new URL(net);
    } catch (MalformedURLException e) {
    e.printStackTrace();
    }
    try {
    httpConnection=(HttpURLConnection) url.openConnection();
    httpConnection.setRequestProperty("RANGE","bytes=" + offset + "-");
    in=httpConnection.getInputStream();
    random = new RandomAccessFile(file,"rw");
    random.seek(offset);
    while(in.read(b)!=-1&&byteread<=len)
    {
    random.write(b);
    byteread+=b.length;
    }
    } catch (IOException e) {
    e.printStackTrace();
    }
    System.out.println("this thread is complete");
    long end= System.currentTimeMillis();
    System.out.println(end-start);
    }
    }
    import java.io.File;
    import java.io.IOException;
    import java.net.HttpURLConnection;
    import java.net.URL;public class b { /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
    ThreadDownload[] d= new ThreadDownload[4];
    Thread[] thread=new Thread[4];
    File file = new File("4.mp3");
    String net ="http://224.cachefile7.rayfile.com/a8c6/zh-cn/preview/e58932fb329b88afe7f4bbe252f70012/preview.mp3";
    URL url=new URL(net);
    HttpURLConnection http = (HttpURLConnection) url.openConnection();
    int length=http.getContentLength();
    System.out.println(length/4);
    System.out.println(http.getContentType());
    d[0]=new ThreadDownload(net, file, length*0,  length/4);
    d[1]= new ThreadDownload(net,file,length/4,length/4);
    d[2]= new ThreadDownload(net,file,length/2,length/4);
    d[3]= new ThreadDownload(net,file,length/4*3,length/4);

    for(int i=0;i<4;i++){
    thread[i]=new Thread(d[i]);
    thread[i].start();
    }
    }
    }
    实验的代码 能改一下么
      

  2.   

    RandomAccessFile是可以获得lock的.
    在写之前,先获得要写入数据位置的lock.这样别人就动不了这块地方了.
    写完之后unlock.接口就在RandomAccessFile里,lz自己找找吧:)
      

  3.   

    哦 原来要用FileLock啊  原来是这个样子 明白了 谢谢了啊~~