zoukankan      html  css  js  c++  java
  • java nio 读取大文件

    package com.yao.bigfile;
    
    import java.io.File;
    import java.io.IOException;
    import java.io.RandomAccessFile;
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    
    public class ReadBig {
    
        public static final String fileName = "D://log//192.168.56.1_debug_.log_2014-12-04";
    
        public static void main(String[] args) throws IOException {
    
            final int BUFFER_SIZE = 0x300000;// 缓冲区大小为3M
    
            File file = new File(fileName);
    
            /**
             * map(FileChannel.MapMode mode,long position, long size) mode -
             * 根据是按只读、读取/写入或专用(写入时拷贝)来映射文件,分别为 FileChannel.MapMode 类中所定义的
             * READ_ONLY、READ_WRITE 或 PRIVATE 之一 position - 文件中的位置,映射区域从此位置开始;必须为非负数
             * size - 要映射的区域大小;必须为非负数且不大于 Integer.MAX_VALUE
             * 所以若想读取文件后半部分内容,如例子所写;若想读取文本后1
             * /8内容,需要这样写map(FileChannel.MapMode.READ_ONLY,
             * f.length()*7/8,f.length()/8)
             * 想读取文件所有内容,需要这样写map(FileChannel.MapMode.READ_ONLY, 0,f.length())
             */
            RandomAccessFile raf = new RandomAccessFile(file, "r");
            MappedByteBuffer inputBuffer = raf.getChannel().map(FileChannel.MapMode.READ_ONLY, file.length() / 2, file.length() / 2);
    
            byte[] dst = new byte[BUFFER_SIZE];// 每次读出3M的内容
    
            long start = System.currentTimeMillis();
    
            for (int offset = 0; offset < inputBuffer.capacity(); offset += BUFFER_SIZE) {
    
                if (inputBuffer.capacity() - offset >= BUFFER_SIZE) {
    
                    for (int i = 0; i < BUFFER_SIZE; i++)
    
                        dst[i] = inputBuffer.get(offset + i);
    
                } else {
    
                    for (int i = 0; i < inputBuffer.capacity() - offset; i++)
    
                        dst[i] = inputBuffer.get(offset + i);
    
                }
    
                int length = (inputBuffer.capacity() % BUFFER_SIZE == 0) ? BUFFER_SIZE : inputBuffer.capacity() % BUFFER_SIZE;
    
                System.out.println(new String(dst, 0, length));// new
                // String(dst,0,length)这样可以取出缓存保存的字符串,可以对其进行操作
    
            }
    
            raf.close();
            long end = System.currentTimeMillis();
    
            System.out.println("读取文件文件一半内容花费:" + (end - start) + "毫秒");
    
        }
    
    }
     
  • 相关阅读:
    python学习笔记(二十三)私有方法和私有属性
    python学习笔记(二十二)实例变量、实例方法、类变量、类方法、属性方法、静态方法
    python学习笔记(二十一)构造函数和析构函数
    python学习笔记(二十)初识面向对象
    大型网站系统架构的演化
    订单系统中并发问题和锁机制的探讨
    利用log4j+mongodb实现分布式系统中日志统一管理
    怎样编写高质量的java代码
    十五分钟学会用Hessian
    Apache Mina实战
  • 原文地址:https://www.cnblogs.com/firstdream/p/5536008.html
Copyright © 2011-2022 走看看