Java BIO NIO对文件的操作

CharBuffer:抽象类 通过CharBuffer.allocate()获取 HeapCharBuffer 类型   toString方法实现:new String(char[],开始位置,截取长度);

BtyeBuffer:抽象类,同上,通过Charset.newDecode()(返回CharsetDecode类).Decode(btyebuffer,charbuffer,true);进行转换, NIO对文件的操作如下:

   import java.io.*;

import java.nio.ByteBuffer;

import java.nio.CharBuffer;

import java.nio.channels.FileChannel;

import java.nio.charset.Charset;

import java.nio.charset.CharsetDecoder;



/**

 * @description  用于学习NIO

 * @author:jiemoren

 * @time: 2020/9/20 13:39

 */

public class NioStudy {

    @Test

    public void nioRead(){

        ByteBuffer byteBuffer=null;

        //这里为了节省执行时间使用StringBuilder

        //StringBuilder stringBuilder=new StringBuilder();

        //为了节省系统扩容StringBuilderchar[]value的性能

        File file=new File("C:\\Users\\MSI-NB\\Desktop\\服务和应用.bat");

        StringBuilder stringBuilder=new StringBuilder((int) file.length());

        try {

            //创建InputStream

            FileInputStream inputStream=new FileInputStream(file);

            //获取Channel

            FileChannel fileChannel=inputStream.getChannel();

            //获取utf-8的字符编码集

            Charset charset=Charset.forName("utf-8");

            //通过utf-8字符编码集创建编码解析器

            CharsetDecoder charsetDecoder=charset.newDecoder();

            int capacity=1024;

            //这里使用直接内存,不归gc,需要手动释放内存

            byteBuffer=ByteBuffer.allocateDirect(capacity);

            //使用堆内存的方式

            //byteBuffer=ByteBuffer.allocate(capacity);

            CharBuffer charBuffer=CharBuffer.allocate(capacity);

            int lenght=-1;

            while ((lenght=fileChannel.read(byteBuffer))!=-1){

                charsetDecoder.decode(byteBuffer,charBuffer,true);

                //这里的toString()方法通过new String(char[] c.int start,int end)创建返回

                stringBuilder.append(charBuffer.toString());

                //情况buffer

                byteBuffer.clear();

            }



        } catch (FileNotFoundException e) {

            e.printStackTrace();

        } catch (IOException e) {

            e.printStackTrace();

        } finally {

            //清除直接内存

            ((DirectBuffer)byteBuffer).cleaner().clean();

        }

        System.out.println(stringBuilder.toString());

    }

}
 
  1. MappedByteBuffer 类底层继承了ByteBuffer ,其核心为map方法实现把物理内存虚拟为运行内存,省略一次拷贝,直接拷贝给用户内存,从而跳过IO读写需要把物理内存加载到运行内存在拷贝到用户内存的两次拷贝过程
  2. class LargeMappedFiles {
  3.     static int length = 0x8FFFFFF; //128MB
  4.  
  5.     public static void main(String[] args) throws Exception{
  6.         MappedByteBuffer out = new RandomAccessFile("test.dat","rw").getChannel()
  7.                 .map(FileChannel.MapMode.READ_WRITE,0,length);
  8.         for (int i = 0; i < length;i++){
  9.             out.put((byte)'x');
  10.         }
  11.         System.out.print("Finished writing");
  12.         for (int i = length/2; i<length/2+6;i++){
  13.             System.out.print(out.get(i));
  14.         }
  15.     }
  16. }
 
 

BIO 文件操作

   public static String bioRead(String fileName) throws IOException {

    long startTime = System.currentTimeMillis();

    try {

        FileReader reader = new FileReader(fileName);



        StringBuffer buf = new StringBuffer();
//使用char字符流

        //char[] cbuf = new char[BF_SIZE];
//使用字节流
byte []b=new btye[BF_SIZE]

        while (reader.read(b) != -1) {
//new String(byte[]b,int sart,int end);中使用
//实现了CharsetDecodeStringCoding来实现bytechar的转换
buf.append(new String(b,0,b.length));

        }

        reader.close();

        return buf.toString();

    } finally {

        System.out.println("使用BIO读取文件耗时:" + (System.currentTimeMillis() - startTime) + "毫秒");

    }

}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值