/** * Maps blah file with a random offset and checks to see if read from the ByteBuffer gets the * right line number */ private static void testRead() throws Exception { StringBuilder sb = new StringBuilder(); sb.setLength(4); for (int x = 0; x < 1000; x++) { try (FileInputStream fis = new FileInputStream(blah)) { FileChannel fc = fis.getChannel(); long offset = generator.nextInt(10000); long expectedResult = offset / CHARS_PER_LINE; offset = expectedResult * CHARS_PER_LINE; MappedByteBuffer b = fc.map(MapMode.READ_ONLY, offset, 100); for (int i = 0; i < 4; i++) { byte aByte = b.get(i); sb.setCharAt(i, (char) aByte); } int result = Integer.parseInt(sb.toString()); if (result != expectedResult) { err.println("I expected " + expectedResult); err.println("I got " + result); throw new Exception("Read test failed"); } } } }
/** * Maps blah file with a random offset and checks to see if data written out to the file can be * read back in */ private static void testWrite() throws Exception { StringBuilder sb = new StringBuilder(); sb.setLength(4); for (int x = 0; x < 1000; x++) { try (RandomAccessFile raf = new RandomAccessFile(blah, "rw")) { FileChannel fc = raf.getChannel(); long offset = generator.nextInt(1000); MappedByteBuffer b = fc.map(MapMode.READ_WRITE, offset, 100); for (int i = 0; i < 4; i++) { b.put(i, (byte) ('0' + i)); } for (int i = 0; i < 4; i++) { byte aByte = b.get(i); sb.setCharAt(i, (char) aByte); } if (!sb.toString().equals("0123")) throw new Exception("Write test failed"); } } }
private static String byteArrayToHex(byte[] a) { StringBuilder sb = new StringBuilder(a.length * 2); for (byte b : a) { sb.append(String.format("%02x", b & 0xff)); } return sb.toString(); }