小编典典

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

javascript

用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.");   


阅读 474

收藏
2020-09-27

共1个答案

小编典典

我将使用足够快的内存映射文件来在同一线程中执行。

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

// when finished
channel.close();

这假定文件小于2 GB,并且将花费10毫秒或更短的时间。

2020-09-27