/*
通过nio的方式对文件进行读取复制
*/
@Test
public void copyFileByNoi() throws IOException {
//获取输入流和输出流
FileInputStream in = new FileInputStream("a.txt");
FileOutputStream out = new FileOutputStream("b.txt");
//获取nio中的通道
FileChannel inChannel = in.getChannel();
FileChannel outChannel = out.getChannel();
//指定缓冲区大小
ByteBuffer buffer = ByteBuffer.allocate(1024);
//将通道的数据写入缓冲区中
while (inChannel.read(buffer)!=-1){
//切换为读取数据的模式
buffer.flip();
//将缓冲区中的数据写入到输出流中
outChannel.write(buffer);
//清空缓冲区
buffer.clear();
}
//关闭资源
out.close();
in.close();
outChannel.close();
inChannel.close();
}
基于Nio方式实现文件的复制
最新推荐文章于 2022-06-19 23:25:27 发布