我们都知道nio中传送数据使用channel+buffer,大的数据可以使用allocateDirect申请直接内存传输以提高效率。
@Test
public void testNIOFile() {
long start = System.currentTimeMillis();
try (FileInputStream is = new FileInputStream("D:\\CCleaner\\CCleaner.exe");
FileOutputStream os = new FileOutputStream("C:/test.exe");
FileChannel ic = is.getChannel();
FileChannel oc = os.getChannel()) {
ByteBuffer buffer = ByteBuffer.allocateDirect(1024 * 1024 * 1024);
ic.read(buffer);
buffer.flip();
oc.write(buffer);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("传输完成" + (System.currentTimeMillis() - start));
}
而NIO包中还提供了更简便的方法,就是channel的transferTo和transferFrom方法
@Test
public void testTransferTo() {
TimeUtil.start();
try (FileInputStream fis = new FileInputStream("F:\\test\\x64q.rpf");
FileOutputStream fos = new FileOutputStream("F:\\x64q.rpf");
FileChannel isc = fis.getChannel();
FileChannel osc = fos.getChannel();
) {
isc.transferTo(0,isc.size(),osc);
// osc.transferFrom(isc,0, isc.size());
} catch (Exception e) {
e.printStackTrace();
}
TimeUtil.end();
}
而测试大文件时发现TransferTo的对象如果大于2GB的话,只会传送2GB,导致数据丢失,而TransferFrom不会出现这个情况,找资料发现使用while可以传送完,具体原因看这个博客:使用transferTo方法限制文件传输大小的原因分析_狗灬的博客-CSDN博客_transferto 大小