標籤:
- MappedByteBuffer是java nio引入的檔案記憶體映射方案,讀寫效能極高。在NIO中主要用到普通的輸入資料流,帶緩衝的輸入資料流,RandomAccessFile和MappedByteBuffer。
現在我們來看看這四種流的效率,廢話少說直接上代碼。
我們採用CRC32來迴圈冗餘校正。CRC32在java.util.zip包中。
1.普通的輸入資料流。
public static long checksumInputStream(Path filename) throws IOException { try (InputStream in = Files.newInputStream(filename)) { CRC32 crc = new CRC32(); int c; while ((c = in.read()) != -1) crc.update(c); return crc.getValue(); } }
2.帶緩衝的輸入資料流
public static long checksumBufferedInputStream(Path filename) throws IOException { 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(); } }
3.RandomAccessFile
public static long checksumRandomAccessFile(Path filename) throws IOException { try (RandomAccessFile file = new RandomAccessFile(filename.toFile(), "r")) { long length = file.length(); CRC32 crc = new CRC32(); for (long p = 0; p < length; p++) { file.seek(p); int c = file.readByte(); crc.update(c); } return crc.getValue(); } }
4.MappedByteBuffer
public static long checksumMappedFile(Path filename) throws IOException { 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 p = 0; p < length; p++) { int c = buffer.get(p); crc.update(c); } return crc.getValue(); } }
每個流對應的方法寫好之後我們來開始測試
public static void main(String[] args) throws IOException { String name = "txt.txt"; Path filename = Paths.get(name); long start, crcValue, end; System.out.println("Input Stream:"); start = System.currentTimeMillis(); crcValue = checksumInputStream(filename); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); System.out.println("Buffered Input Stream:"); start = System.currentTimeMillis(); crcValue = checksumBufferedInputStream(filename); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); System.out.println("Random Access File:"); start = System.currentTimeMillis(); crcValue = checksumRandomAccessFile(filename); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); System.out.println("Mapped File:"); start = System.currentTimeMillis(); crcValue = checksumMappedFile(filename); end = System.currentTimeMillis(); System.out.println(Long.toHexString(crcValue)); System.out.println((end - start) + " milliseconds"); }
為了保證每種流相互之間對結果沒有影響,我們可以分別把main方法中其他流的代碼注釋掉。
最後可以看到MappedByteBuffer效率最高,所消耗的時間最少。
Java 記憶體對應檔MappedByteBuffer