java 实现多线程下载(2)(二)

2014-11-24 09:44:18 · 作者: · 浏览: 1
, "bytes="+this.offset+"-"+(this.offset+this.length-1));
BufferedInputStream bis=new BufferedInputStream(httpURLConnection.getInputStream());
byte [] buff=new byte[1024];
int bytesRead;
while (-1!=(bytesRead=bis.read(buff, 0, buff.length))) {
this.writeFile(file, offset, buff, bytesRead);
this.offset=this.offset+bytesRead;
}
} catch (IOException e) {
e.printStackTrace();
}
}
//将字节数组以随机存取方式写入文件
//fileName是被写入的文件
//offset代表写入文件的位置偏移量
//bytes是待写入的字节数组
//realLength是实际需要写入的字节数(realLength<=bytes.length)
private void writeFile(String fileName,long offset,byte[] bytes,int realLength)throws IOException
{
File newFile =new File(fileName);
RandomAccessFile raf=new RandomAccessFile(newFile, "rw");
raf.seek(offset);
raf.write(bytes, 0, realLength);
raf.close();
}
}