代码如下:
先演示先 Buffer
的使用,代码如下:
public static void main1(String[] args) {
IntBuffer allocate = IntBuffer.allocate(5);
allocate.put(30);
allocate.put(34);
Buffer flip = allocate.flip();
while (flip.hasRemaining()) {
System.out.println(allocate.get());
}
}
方法一:Java 使用 Channel
通道实现快速拷贝文件方法:
public static void main222(String[] args) throws Exception {
FileInputStream fileInputStream = new FileInputStream("/Users/Desktop/file.txt");
FileChannel sourceChannel = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream("/Users/Desktop/file4.txt");
FileChannel destChannel = fileOutputStream.getChannel();
// destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
sourceChannel.transferTo(0, sourceChannel.size(), destChannel);
fileInputStream.close();
fileOutputStream.close();
}
transferTo()
方法底层使用了 零拷贝 方法提升了性能
方法二:ByteBuffer
+ Channel
结合的方式实现文件拷贝
public static void main11(String[] args) {
FileInputStream fileInputStream = null;
try {
fileInputStream = new FileInputStream("/Users/gongweiming/Desktop/file.txt");
FileChannel channel = fileInputStream.getChannel();
FileOutputStream fileOutputStream = new FileOutputStream("/Users/gongweiming/Desktop/file2.txt");
FileChannel outChannel = fileOutputStream.getChannel();
ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
while (true) {
// 注意必须复位 Position Limit,否则 len 永远返回 0,因为 Postion 和 limit 相等
byteBuffer.clear();
int len = channel.read(byteBuffer);
if (len == -1) {
break;
}
// 反转
byteBuffer.flip();
outChannel.write(byteBuffer);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}