直接缓存
直接缓存相比与缓存而言,加快了I/O速度,使用一种特殊方式为其分配内存的缓冲区,原本硬盘与应用程序之间信息的交互是通过内核地址空间与用户地址空间,两者里面开辟各开辟一个缓存区,这便是ByteBuffer.allocation(int capacity)方法的实现,而直接缓存是通过开辟一个物理内存,从而硬盘与应用程序之间的交互只存在物理内存这一层,避免了将缓存区的内容拷贝到一个中间缓存区或者从一个中间缓存区拷贝数据。
public class DirectDemo {
public static void main(String[] args) throws IOException {
//从系统硬盘中读取文件内容
String file="E://a.txt";
FileInputStream fileInputStream = new FileInputStream(file);
FileChannel channel = fileInputStream.getChannel();
//直接申请物理内存
ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
//向系统硬盘中读入文件内容
FileOutputStream fileOutputStream = new FileOutputStream("E://b.txt");
FileChannel channel1 = fileOutputStream.getChannel();
while (true){
buffer.clear();
//数据读入到直接缓存中
int read = channel.read(buffer);
if (read==-1){
break;
}
buffer.flip();
//数据从缓存中读入到硬盘中
channel1.write(buffer);
}
}
}
内存映射
内存映射是一种读和写文件数据的方法,可以比常规的基于流或者通道的I/O快得多,内存映射文件I/O通过使文件中的数据表现为内存数组的内容来实现,也就是说把缓冲区跟文件系统进行一个映射关联,只要操作缓冲区里面的内容,文件内容也会跟着改变
public class FileMapper {
public static void main(String[] args) throws IOException {
RandomAccessFile file = new RandomAccessFile("E://a.txt","wr");
FileChannel channel = file.getChannel();
MappedByteBuffer map = channel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
map.put(0,(byte)79);
file.close();
}
}