FileChannel实现的简单断点复制

来源:互联网 发布:nginx windows安装 编辑:程序博客网 时间:2024/06/18 07:10

首先是一个简单的复制100个字节的数据

public void copy() {try {int lenPos = 0;int copySize = 0;String sourcePath = "test.ziptemp";String targetPath = "download/test.zip";FileChannel in = new FileInputStream(sourcePath).getChannel(), out = new RandomAccessFile(targetPath, "rw").getChannel();//System.out.println("源文件MD5:"+ MD5Util.getFileMD5String(new File(sourcePath)));System.out.println("源文件大小:" + new File(sourcePath).length());ByteBuffer buff = ByteBuffer.allocate(10);in.position(lenPos);out.position(lenPos);int nRead;while ((nRead = in.read(buff)) > 0) {buff.flip();out.write(buff);copySize += nRead;if(copySize == 100) {  break;}buff.clear();}System.out.println("复制大小:" + copySize);//System.out.println("目标文件MD5:"+ MD5Util.getFileMD5String(new File(targetPath)));System.out.println("目标文件大小:" + new File(targetPath).length());out.close();in.close();} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("Finish");}


然后将
if(copySize == 100) {break;}
这一段注释

然后将lenPos改为100

再运行一次,就能完成断点复制了


此方法也能够运用到http、ftp或其他形式的复制

原创粉丝点击