Dump a file to a HEX fileTag(s): IO


import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.IOException;
import java.io.PrintStream;

public class FileUtils {

  public static void hexDump(PrintStream out, File file) throws IOException {
      InputStream is = new FileInputStream(file);
      int i = 0;
 
      while (is.available() > 0) {
        StringBuilder sb1 = new StringBuilder();
        StringBuilder sb2 = new StringBuilder("   ");
        out.printf("%04X  ", i * 16);
        for (int j = 0; j < 16; j++) {
           if (is.available() > 0) {
             int value = (int) is.read();
             sb1.append(String.format("%02X ", value));
             if (!Character.isISOControl(value)) {
               sb2.append((char)value);
             }
             else {
               sb2.append(".");
             }
           }
           else {
             for (;j < 16;j++) {
               sb1.append("   ");
             }
           }
        }
        out.print(sb1);
        out.println(sb2);
        i++;
      }
      is.close();
  }

  
  public static void main(String args[]) throws Exception {
    // dump to the console
    FileUtils.hexDump(System.out, new File("c:/temp/nvir.log"));
    // dump to a file
    FileUtils.hexDump(new java.io.PrintStream("c:/temp/nvir.hex"), new File("c:/temp/nvir.log"));
    System.out.println("Done.");
  }  
}
The output looks like this :
...
343E0  43 41 54 49 4F 4E 20 44 41 54 41 5C 4D 4F 5A 49    CATION DATA\MOZI
343F0  4C 4C 41 5C 50 52 4F 46 49 4C 45 53 5C 44 45 46    LLA\PROFILES\DEF
34400  41 55 4C 54 5C 43 42 50 4D 53 35 4E 38 2E 53 4C    AULT\CBPMS5N8.SL
34410  54 5C 4D 41 49 4C 5C 4D 41 49 4C 5C 54 52 41 53    T\MAIL\MAIL\TRAS
34420  48 0D 0A 20 20 20 20 20 20 54 68 69 73 20 66 69    H..      This fi
34430  6C 65 20 69 73 20 61 20 6D 61 69 6C 62 6F 78 2E    le is a mailbox.
34440  20 54 6F 20 61 76 6F 69 64 20 69 6D 70 61 63 74     To avoid impact
...

blog comments powered by Disqus