java讀取文件的幾種方式性能比較


    //普通輸入流讀取文件內容
    public static long checksumInputStream(Path filename)
    {
        try(InputStream in= Files.newInputStream(filename))
        {
            CRC32 crc=new CRC32();
            int c;
            while ((c=in.read())!=-1) 
            {
                crc.update(c);
            }
            return crc.getValue();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return 0;
        }
    }
    
    //帶有緩沖讀取文件
    public static long checkSumBufferedInputStream(Path filename)
    {
        try(InputStream in=new BufferedInputStream(Files.newInputStream(filename)))
        {
            CRC32 crc=new CRC32();
            int c;
            while ((c=in.read())!=-1) 
            {
                crc.update(c);
            }
            return crc.getValue();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }
    
    //隨機讀取文件
    public static long checksumRandomAccessFile(Path filename)
    {
        try(RandomAccessFile file=new RandomAccessFile(filename.toFile(), "r"))
        {
            long length=file.length();
            CRC32 crc=new CRC32();
            for (int i = 0; i < length; i++) {
                file.seek(i);
                int c=file.readByte();
                crc.update(c);
            }
            return crc.getValue();
        } catch (FileNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }
    
    //通過磁盤映射讀取文件
    public static long checksumMappedFile(Path filename) 
    {
        try(FileChannel channel=FileChannel.open(filename))
        {
            CRC32 crc=new CRC32();
            int length=(int)channel.size();
            MappedByteBuffer buffer= channel.map(FileChannel.MapMode.READ_ONLY, 0, length);
            for (int i = 0; i <length; i++) 
            {
                int c=buffer.get(i);
                crc.update(c);
            }
            return crc.getValue();
            
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return 0;
    }

普通輸入流:68513ms

帶緩沖的方式:116ms

隨機訪問讀取:81203ms

磁盤映射讀取方式:102ms


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM