how to show the hex detail of a file in java code example

Example: how to show the hex detail of a file in java

//Just some image on my hard drive
File file = new File("C:\\Users\\%username%\\Pictures\\Memes\\What_If_I_Told_You.jpg");
StringBuilder builder = new StringBuilder();
try {
    FileInputStream fin = new FileInputStream(file);
    byte[] buffer = new byte[1024];
    int bytesRead = 0;
    while((bytesRead = fin.read(buffer)) > -1)
        for(int i = 0; i < bytesRead; i++)
            builder.append(String.format("%02x", buffer[i] & 0xFF)).append(i != bytesRead - 1 ? " " : "");
} catch (IOException e) {
    e.printStackTrace();
}
System.out.println(builder.toString());

Tags:

Misc Example