transferFrom()和transferTo()
transferFrom()
transferFrom()将数据从源通道传输到其他 Channel 中:
RandomAccessFile fromFile = null;
FileChannel fromChannel = null;
RandomAccessFile toFile = null;
FileChannel toChannel = null;
try {
fromFile = new RandomAccessFile("D:/1.txt", "rw");
fromChannel = fromFile.getChannel();
toFile = new RandomAccessFile("D:/2.txt", "rw");
toChannel = toFile.getChannel();
// 定义传输位置
long position = 0L;
// 最多传输的字节数
long count = fromChannel.size();
//将数据从源通道传输到另一个通道
toChannel.transferFrom(fromChannel, position, count);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
transferTo()
transferTo()将数据从源通道传输到其他 Channel 中:
RandomAccessFile fromFile = null;
FileChannel fromChannel = null;
RandomAccessFile toFile = null;
FileChannel toChannel = null;
try {
fromFile = new RandomAccessFile("D:/1.txt", "rw");
fromChannel = fromFile.getChannel();
toFile = new RandomAccessFile("D:/2.txt", "rw");
toChannel = toFile.getChannel();
// 定义传输位置
long position = 0L;
// 最多传输的字节数
long count = fromChannel.size();
// 将数据从源通道传输到另一个通道
fromChannel.transferTo(position, count, toChannel);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}