FileChannel的map()方法可以将磁盘上的文件映射到计算机的虚拟内存中,并将虚拟内存包装成一个MappedByteBuffer对象。输出流的FileChannel通过write(MappedByteBuffer对象)方法可以将文件写出到指定位置。该方法不需要频繁的磁盘输入输出,提高I/O流的读写效率。但计算机的虚拟内存会严重影响该种方式。
package com.wang.TestBuffer;
import java.io.*;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
public class Test04 {
public static void main(String[] args) {
File file = new File("D:\\IdeaProjects\\TestNIO\\src\\main\\java\\com\\wang\\TestBuffer\\Test04.java");
try(
FileInputStream fileInputStream = new FileInputStream(file);
FileOutputStream fileOutputStream = new FileOutputStream("D:\\IdeaProjects\\TestNIO\\src\\main\\java\\com\\wang\\TestBuffer\\Test04.txt");
FileChannel inChannel =fileInputStream.getChannel();
FileChannel outChannel = fileOutputStream.getChannel();
) {
MappedByteBuffer buffer = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, file.length());
//写出操作
outChannel.write(buffer);
//翻转,进行读取操作
buffer.flip();
//解码
Charset charset =Charset.defaultCharset();
System.out.println(charset.decode(buffer));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}