Skip to content

Instantly share code, notes, and snippets.

@Crydust
Created July 14, 2015 17:09
Show Gist options
  • Save Crydust/f01577321fe481985710 to your computer and use it in GitHub Desktop.
Save Crydust/f01577321fe481985710 to your computer and use it in GitHub Desktop.
test with files
private static void printBytesAsByteArray(String name, byte[] bytes) {
StringBuilder sb = new StringBuilder();
sb.append("byte[] ").append(name).append(" = new byte[] {");
if (bytes.length != 0) {
int i = 0;
for (byte aByte : bytes) {
if (i == 0) {
sb.append("\n ");
}
i++;
if (i == 10) {
i = 0;
}
sb.append(String.format("(byte) 0x%02x, ", aByte));
}
sb.setLength(sb.length() - 2);
sb.append('\n');
}
sb.append("};\n");
System.out.println(sb);
}
private static void printBytesWithLegibleStrings(String name, byte[] bytes) {
StringBuilder sb = new StringBuilder();
sb.append(name).append(" = ").append(bytes.length).append(" bytes:");
if (bytes.length != 0) {
int i = 0;
for (byte aByte : bytes) {
if (i == 0) {
sb.append("\n");
}
i++;
if (i == 200) {
i = 0;
}
if (aByte >= 0x20 && aByte <= 0x7e) {
sb.append((char) aByte);
} else {
sb.append('.');
}
}
sb.append('\n');
}
sb.append('\n');
System.out.println(sb);
}
private void writeFile(String name, byte[] bytes) throws FileNotFoundException, IOException {
File folder = new File("src/test/resources", getClass().getPackage().getName().replace('.', '/'));
folder.mkdirs();
OutputStream os = null;
try {
os = new BufferedOutputStream(new FileOutputStream(new File(folder, name)));
os.write(bytes);
os.close();
} finally {
if (os != null) {
os.close();
}
}
}
private byte[] readFile(String name) throws IOException {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream is = null;
try {
is = new BufferedInputStream(getClass().getResourceAsStream(name));
int b;
while ((b = is.read()) != -1) {
bos.write(b);
}
} finally {
if (is != null) {
is.close();
}
}
return bos.toByteArray();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment