一、通过Channel和Buffer拷贝文件
@Test public void channelCopyFile() throws IOException { FileInputStream fis = new FileInputStream("e:\\老文件.jpg"); FileChannel fisChannel = fis.getChannel(); FileOutputStream fos = new FileOutputStream("e:\\新文件.jpg"); FileChannel channel = fos.getChannel(); ByteBuffer bf = ByteBuffer.allocate(512); // 从老通道循环读取数据 while (fisChannel.read(bf) != -1) { // 反转缓冲区 bf.flip(); // 写入新通道 channel.write(bf); bf.clear(); } // 关闭流 fos.close(); fis.close(); System.out.println("over"); }
二、transferTo
@Test public void TransferTo() throws IOException { FileInputStream fis = new FileInputStream("e:\\222.jpg"); FileChannel fisChannel = fis.getChannel(); FileOutputStream fos = new FileOutputStream("e:\\新文件.jpg"); FileChannel channel = fos.getChannel(); fisChannel.transferTo(0, fisChannel.size(), channel); // 关闭流 fos.close(); fis.close(); System.out.println("over"); }
三、transferFrom
1 @Test 2 public void transferFrom() throws IOException { 3 FileInputStream fis = new FileInputStream("e:\\222.jpg"); 4 FileChannel fisChannel = fis.getChannel(); 5 6 FileOutputStream fos = new FileOutputStream("e:\\新文件.jpg"); 7 FileChannel channel = fos.getChannel(); 8 9 channel.transferFrom(fisChannel, 0, fisChannel.size()); 10 // 关闭流 11 fos.close(); 12 fis.close(); 13 System.out.println("over"); 14 }