zoukankan      html  css  js  c++  java
  • NIO之轻松读取大文件

    今天碰到了一个问题,从游戏服务器下载下来的输出log有一个多G大。用记事本打不开,EditPlus也打不开,都提示文件太大。用word也打不开,提示文件大于512M。打不开怎么查找错误啊。于是他问我解决办法。我想了想,决定写一个简单的程序读取这个log,把这个log切分成一些小的可以用Editplus打开的文本。正好前段时间看了一些NIO的东西,所以决定用NIO来写。没想到,10几行代码就搞定了。下面附上源代码:
    ReadLargeTextWithNIO.java
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    /**
     *
     * 用NIO读取大文本(1G以上)
     *
     * @author landon
     *
     */
    public class ReadLargeTextWithNIO
    {
     public static void main(String...args) throws IOException
     {
      FileInputStream fin = new FileInputStream("d:\temp\outlineA1.log");
      FileChannel fcin = fin.getChannel();
      
      ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 50);
      
      while(true)
      {
       buffer.clear();
       
       int flag = fcin.read(buffer);
       
       if(flag == -1)
       {
        break;
       }
       
       buffer.flip();
       
       FileOutputStream fout = new FileOutputStream("d:\temp\" + Math.random() + ".log");
       FileChannel fcout = fout.getChannel();
       
       fcout.write(buffer);
      }
     }
    }
    
    下面简单说几个注意的地方:
    a.因为要把超大文本切分成小的部分,所以分配buffer的时候尽量大一些,这里我分配的大小是50M,不过如果太大了,可能会报内存溢出。
    b.说一下clear和flip的方法,直接上源码:
    public final Buffer clear()
    {
    position = 0;
    limit = capacity;
    mark = -1;
    return this;
    }
    
    public final Buffer flip()
    {
    limit = position;
    position = 0;
    mark = -1;
    return this;
    }
    一看便知二者的区别。
    c.跳出循环也即读完的判断是read返回的flag是-1
  • 相关阅读:
    【C++】C++代码动态检查
    【加解密】使用CFSSL生成证书并使用gRPC验证证书
    分库分表下跨库join解决方案
    解决1235
    为什么v-for中的key值不推荐使用index
    弹性布局公共样式总结
    关于python的模块
    [转]Ubuntu18.04安装uwsgi错误:error: lto-wrapper failed collect2: error: ld returned 1 exit status
    python 坐标遍历 生成笛卡尔积矩阵
    Mongo BsonUndefined 转换问题(自定义Mongo类型转换器)
  • 原文地址:https://www.cnblogs.com/wh-king/p/4324722.html
Copyright © 2011-2022 走看看