Can somebody please try and help me speed up my code? The file is ~12MB (you can download it here). It takes around 500-600 milliseconds to run on my i7 4790k.
import java.io.FileInputStream;
import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayDeque;
import java.util.Deque;
/**
* Created by Jonathan on 4/1/2016.
*/
public class HexDumper {
public static void main(String[] args) throws Exception {
Deque<String> lines = new ArrayDeque<>(1_000_000);
lines.add("Address 00 01 02 03 04 05 06 07 08 09 0A 0B 0C 0D 0E 0F\n");
long s = System.currentTimeMillis();
FileChannel channel = new FileInputStream("client.dll").getChannel();
ByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
byte[] bytes = new byte[16];
int offset = 0;
while (buffer.remaining() > 0) {
buffer.get(bytes);
lines.add(new DataRow(offset, bytes).toString());
offset += 16;
}
System.out.println(System.currentTimeMillis() - s);
Files.write(Paths.get("dump.txt"), lines);
}
public static class DataRow {
private final int offset;
private final byte[] values;
public DataRow(int offset, byte[] values) {
this.offset = offset;
this.values = values;
}
public int offset() {
return offset;
}
public byte[] values() {
return values;
}
private final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
private static String bytesToHex(byte[] bytes, int bundleSize) {
char[] hexChars = new char[(bytes.length * 2) + (bytes.length / bundleSize)];
for (int j = 0, k = 1; j < bytes.length; j++, k++) {
int v = bytes[j] & 0xFF;
int idx = (j * 2) + j / bundleSize;
hexChars[idx] = HEX_ARRAY[v >>> 4];
hexChars[idx + 1] = HEX_ARRAY[v & 0x0F];
if ((k % bundleSize) == 0) {
hexChars[idx + 2] = ' ';
}
}
return new String(hexChars).trim();
}
@Override
public String toString() {
String row = "0000000000000" + bytesToHex(BigInteger.valueOf(offset).toByteArray(), 4);
row = row.substring(row.length() - 8) + " ";
row += bytesToHex(values, 1);
return row;
}
}
}
Is it possible to make it dump the hex values any faster? I've tried other hex editors both Java and C++ and they seem to scan the file instantly.