LogFileHandler extends Handler { public void writeEscapedBytes(byte[] bytes) throws IOException { int magic = 0; for (byte b : bytes) if (b == MAGIC_BYTE || b == MAGIC_BYTE + 1) magic++; byte eBytes[] = new byte[bytes.length + magic]; int i = 0; for (byte b : bytes) { if (b == MAGIC_BYTE || b == MAGIC_BYTE + 1) { eBytes[i++] = MAGIC_BYTE + 1; eBytes[i++] = (byte) (b - MAGIC_BYTE); } else { eBytes[i++] = b; } } byte[] lenBytes = ByteBuffer.allocate(4).putInt(bytes.length).array(); synchronized (mLogFile) { mLogFile.write(MAGIC_BYTE); mLogFile.write(lenBytes); mLogFile.write(eBytes); } } LogFileHandler(Looper looper); @Override void handleMessage(Message msg); void writeEscapedBytes(byte[] bytes); static String bytesToHex(byte[] bytes, int len); static final int LOG_MESSAGE; static final int MAGIC_BYTE; static final String LOGFILE_NAME; }
@Test public void testWriteByteArray() throws IOException { ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); lfh.setLogFile(byteArrayOutputStream); lfh.writeEscapedBytes(testUnescaped); byte[] result = byteArrayOutputStream.toByteArray(); Assert.assertTrue(Arrays.equals(expectedEscaped, result)); }