日期:2014-05-17  浏览次数:20857 次

java http 分段下载
大家好,我是java小白,最近研究了http分段下载,但是自己写的代码运行后下载的文件不能打开。文件数据大小和网上文件是一样的,所以我没有找到原因,在此求教,谢谢。
以下是我的函数,
Java code
public String upload(URL url) throws IOException{
        String fileName = url.getFile();
        InputStream in = null;
        final long size = 1024*5;

        if(fileName.equals("")){
            throw new IOException("upload webfile \"" + fileName + "\" failed");
        }
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        long total = con.getContentLength();
        System.out.println("file size is "+total);
        String newFileName = null;
        con.disconnect();
        if(total<=size){
            con = (HttpURLConnection) url.openConnection();
            con.connect();
            in = con.getInputStream();
            
            return upload(fileName, in);
            
        }else {
            
            
            long part = total%size != 0 ? total/size+1 : total/size;
            long len;
            byte[] b = null;
            for(int i = 0; i< part;i++){
                len = i!=part-1 ? size : total%size;
                b = new byte[IoUtils.safeLongToInt(len)];
                //con.setConnectTimeout(30000);
                con.setReadTimeout(30000);
                 //设置传输位置 
                con.setRequestProperty("RANGE","bytes=" + i*size + "-" + (i*size+len-1)    + "/" + total); 
                //设置请求信息
                con.setRequestProperty("GET","/large/774fca33gw1dozmkrsu6ej.jpg HTTP/1.1");
                //设置接受信息
                con.setRequestProperty("[code=Java]Accept
","image/gif,image/x-xbitmap,application/msword,*/*");
  //设置连接信息
  con.setRequestProperty("Connection","Keep-Alive"); 
  //con.setRequestProperty("RANGE","bytes " + i*size + "-" + (i*size+len-1) + "/" + total); 
  // 获得输入流 
  con.connect();
  in = con.getInputStream();
  DataInputStream dis = new DataInputStream(in); 
 
  RandomAccessFile oSavedFile = new RandomAccessFile("C:/bbb.jpg","rw");
  //FileOutputStreamWrite fout = new FileOutputStream(oSavedFile);
  long nPos = i*size; 
  // 定位文件指针到 nPos 位置 
  oSavedFile.seek(nPos);
 
  // 从输入流中读入字节流,然后写到文件中 
  dis.read(b,0,IoUtils.safeLongToInt(len));
  oSavedFile.write(b);
  con.disconnect();
 
  }
  in.close();
  return newFileName;
  }
}[/code]

------解决方案--------------------
这里有误 
// 从输入流中读入字节流,然后写到文件中
dis.read(b,0,IoUtils.safeLongToInt(len));

并不是每次你让他读多少他就正好读多少数据进来,所以要在这里做个循环,一直读完。
Java code

        int wlen = 0;
        while (wlen < len) {
            int read = bis.read(b, 0, len);
            wlen += read;
            oSavedFile.write(b, 0, read);
        }