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(); } }
/** Test exceptions specified by map method */ private static void testExceptions() throws Exception { // check exceptions when channel opened for read access try (FileChannel fc = FileChannel.open(blah.toPath(), READ)) { testExceptions(fc); checkException(fc, MapMode.READ_WRITE, 0L, fc.size(), NonWritableChannelException.class); checkException( fc, MapMode.READ_WRITE, -1L, fc.size(), NonWritableChannelException.class, IllegalArgumentException.class); checkException( fc, MapMode.READ_WRITE, 0L, -1L, NonWritableChannelException.class, IllegalArgumentException.class); checkException(fc, MapMode.PRIVATE, 0L, fc.size(), NonWritableChannelException.class); checkException( fc, MapMode.PRIVATE, -1L, fc.size(), NonWritableChannelException.class, IllegalArgumentException.class); checkException( fc, MapMode.PRIVATE, 0L, -1L, NonWritableChannelException.class, IllegalArgumentException.class); } // check exceptions when channel opened for write access try (FileChannel fc = FileChannel.open(blah.toPath(), WRITE)) { testExceptions(fc); checkException(fc, MapMode.READ_ONLY, 0L, fc.size(), NonReadableChannelException.class); checkException( fc, MapMode.READ_ONLY, -1L, fc.size(), NonReadableChannelException.class, IllegalArgumentException.class); /* * implementation/spec mismatch, these tests disabled for now */ // checkException(fc, MapMode.READ_WRITE, 0L, fc.size(), // NonWritableChannelException.class); // checkException(fc, MapMode.PRIVATE, 0L, fc.size(), // NonWritableChannelException.class); } // check exceptions when channel opened for read and write access try (FileChannel fc = FileChannel.open(blah.toPath(), READ, WRITE)) { testExceptions(fc); } }