在Java中读取相对较大的字节文件的最快方法

ott*_*uit 13 java performance file-io

使用Java的I/O方法读取相对较大的文件的最快方法是什么?我当前的解决方案使用BufferedInputStream保存到分配了1024字节的字节数组.然后将每个缓冲区保存在以ArrayList供以后使用.整个过程通过一个单独的线程(可调用接口)调用.

虽然不是很快.

    ArrayList<byte[]> outputArr = new ArrayList<byte[]>();      
    try {
        BufferedInputStream reader = new BufferedInputStream(new FileInputStream (dir+filename));

        byte[] buffer = new byte[LIMIT]; // == 1024 
            int i = 0;
            while (reader.available() != 0) {
                reader.read(buffer);
                i++;
                if (i <= LIMIT){
                    outputArr.add(buffer);
                    i = 0;
                    buffer = null;
                    buffer = new byte[LIMIT];
                }
                else continue;              
            }

         System.out.println("FileReader-Elements: "+outputArr.size()+" w. "+buffer.length+" byte each.");   
Run Code Online (Sandbox Code Playgroud)

Pet*_*rey 39

我会使用一个内存映射文件,它在同一个线程中足够快.

final FileChannel channel = new FileInputStream(fileName).getChannel();
MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());

// when finished
channel.close();
Run Code Online (Sandbox Code Playgroud)

这假定文件小于2 GB并且将花费10毫秒或更少.

  • 该死的!到底为什么那东西速度这么快?无论如何,谢谢,工作完美。(编辑:它从内存中获取文件,java文档刚刚告诉我。聪明) (2认同)
  • 如果您需要访问超过 2 GB 的空间,则需要使用多个映射。 (2认同)