//普通輸入流讀取文件內容 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