Java I/O How to - Display file contents in hexadecimal








Question

We would like to know how to display file contents in hexadecimal.

Answer

//from   w  ww  .ja  va2 s.  c o m
import java.io.FileInputStream;

public class Main {
  public static void main(String[] args) throws Exception {
    FileInputStream fis = new FileInputStream("main.java");
    int i = 0;
    int count = 0;

    while ((i = fis.read()) != -1) {
      if (i != -1) {
        System.out.printf("%02X ", i);
        count++;
      }

      if (count == 16) {
        System.out.println("");
        count = 0;
      }
    }
    fis.close();
  }
}

The code above generates the following result.