public static void main(String args[]) throws IOException {
//获取当前项目路径
String relativelyPath = System.getProperty("user.dir");
System.out.println(relativelyPath);
//创建输入流
FileInputStream input = new FileInputStream(relativelyPath + "/in.txt");
//创建读取管道
ReadableByteChannel source = input.getChannel();
//创建输出流
FileOutputStream output = new FileOutputStream(relativelyPath + "/out.txt");
//创建写入管道
WritableByteChannel destination = output.getChannel();
//复制数据
copyData(source, destination);
source.close();
destination.close();
System.out.println("复制文本内容数据成功!");
}
private static void copyData(ReadableByteChannel src, WritableByteChannel dest) throws IOException {
//定义缓冲区容量
ByteBuffer buffer = ByteBuffer.allocateDirect(20 * 1024);
while (src.read(buffer) != -1) {
// 调换这个buffer的当前位置,并且设置当前位置是0。说的意思就是:将缓存字节数组的指针设置为数组的开始序列即数组下标0。这样就可以从buffer开头,对该buffer进行遍历(读取)了。
buffer.flip();
//判断缓冲区是否还有数据
while (buffer.hasRemaining()) {
dest.write(buffer);
}
//将数据写入输出文件
buffer.clear();
}
}