NIO相对于IO来说,增加了一个通道的 channel
public static void test3() throws Exception {
// 非直接缓冲区复制文件
FileInputStream fileInputStream = new FileInputStream("D://vlc-3.0.3-win64.tmp");
FileOutputStream fileOutputStream = new FileOutputStream("D://vlc-3.0.3-win64-bak.tmp");
FileChannel inChannel = fileInputStream.getChannel();
FileChannel outChannel = fileOutputStream.getChannel();
ByteBuffer b = ByteBuffer.allocate(1024);
while (inChannel.read(b) != -1){
b.flip();
outChannel.write(b);
b.clear();
}
outChannel.close();
inChannel.close();
fileOutputStream.close();
fileInputStream.close();
}
首先就是先创建文件输入流(FileInputStream )和文件输出流(FileOutputStream ),
FileInputStream fileInputStream = new FileInputStream("D://vlc-3.0.3-win64.tmp"); FileOutputStream fileOutputStream = new FileOutputStream("D://vlc-3.0.3-win64-bak.tmp");
输入流和输出流的区别是。输入流从文件中往内存中写入东西,而输出流是从内存中往文件里写入东西。这个输入输出是针对内存而言。我之前就是经常弄反。
根据两个留分别生成对应的通道。
FileChannel inChannel = fileInputStream.getChannel(); FileChannel outChannel = fileOutputStream.getChannel();
创建字符缓冲区数组
ByteBuffer b = ByteBuffer.allocate(1024);
然后就是依次读取,当输入流读的!=-1 就持续读取。
在读取的过程中,往文件中写入数据。
然后把通道和文件IO流关闭即可。