Java IO 在文件读取方面优于 Java NIO

Java IO outperforms Java NIO when it comes to file reading

我相信新的 nio 包在读取文件内容所需的时间方面会优于旧的 io 包。但是,根据我的结果,io 包似乎优于 nio 包。这是我的测试:


import java.io.*;
import java.lang.reflect.Array;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

public class FileTestingOne {

    public static void main(String[] args) {
        long startTime = System.nanoTime();

        File file = new File("hey2.txt");
        try {
            byte[] a = direct(file);
            String s = new String(a);
        }
        catch (IOException err) {
            err.printStackTrace();
        }
        long endTime   = System.nanoTime();
        long totalTime = (endTime - startTime);
        System.out.println(totalTime);
    }

    public static ByteBuffer readFile_NIO(File file) throws IOException {
        RandomAccessFile rFile = new RandomAccessFile(file.getName(), "rw");
        FileChannel inChannel = rFile.getChannel();

        ByteBuffer _buffer = ByteBuffer.allocate(1024);
        int bytesRead = inChannel.read(_buffer);
        while (bytesRead != -1) {
            _buffer.flip();
            while (_buffer.hasRemaining()) {
                byte b = _buffer.get();
            }
            _buffer.clear();
            bytesRead = inChannel.read(_buffer);
        }

        inChannel.close();
        rFile.close();
        return _buffer;
    }

    public static byte[] direct(File file) throws IOException {
        byte[] buffer = Files.readAllBytes(file.toPath());
        return buffer;
    }

    public static byte[] readFile_IO(File file) throws IOException {

        byte[] _buffer = new byte[(int) file.length()];
        InputStream in = null;

        try {
            in = new FileInputStream(file);
            if ( in.read(_buffer) == -1 ) {
                throw new IOException(
                        "EOF reached while reading file. File is probably empty");
            }
        }
        finally {
            try {
                if (in != null)
                    in.close();
            }
            catch (IOException err) {
                // TODO Logging
                err.printStackTrace();
            }
        }
        return _buffer;
    }



}

// Small file
//7566395  -> readFile_NIO
//10790558 -> direct
//707775   -> readFile_IO

// Large file
//9228099  -> readFile_NIO
//737674   -> readFile_IO
//10903324 -> direct

// Very large file
//13700005  -> readFile_NIO
//2837188   -> readFile_IO
//11020507  -> direct

结果是:

我想问这个问题是因为(我相信)nio 包是非阻塞的,因此它需要更快,对吗?

谢谢,

编辑:

将 ms 更改为 ns

内存映射文件(或 MappedByteBuffer)是 Java NIO 的一部分,可以帮助提高性能。

JavaNIO中的非阻塞意味着一个线程不必等待下一个数据的读取。它不一定会影响完整操作的性能(例如读取 处理文件)。