通过nio内存映射文件方式进行读/写操作

        FileChannel的map()方法可以将磁盘上的文件映射到计算机的虚拟内存中,并将虚拟内存包装成一个MappedByteBuffer对象。输出流的FileChannel通过write(MappedByteBuffer对象)方法可以将文件写出到指定位置。该方法不需要频繁的磁盘输入输出,提高I/O流的读写效率。但计算机的虚拟内存大小会严重影响该种方式。

        注意:MappedByteBuffer的capacity容量最大值Integer.MAX_VALUE=2 147 483 647,即最多2g的文件大小。

        Integer.MAX_VALUE表示int数据类型的最大取值数:2 147 483 647;
        Integer.MIN_VALUE表示int数据类型的最小取值数:-2 147 483 648。

        

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();
        }

    }
}

        

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值