How to display file contents into Hexadecimal format in java?

Below java code shows how to convert and display file contents into Hexadecimal format –

 

/****************************************************************************************
 * Created on 03-2012 Copyright(c) http://kodehelp.com All Rights Reserved.
 ****************************************************************************************/
package com.kodehelp.javaio;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;

/**
 * Created by http://kodehelp.com
 * Date: 03/05/2012
 */
public class FileContentToHexadecimal {

	public static void main(String[] args) throws IOException {
		FileInputStream fis = null;
        try {
            // Open the file using FileInputStream
            fis = new FileInputStream("/sample.log");

            // A variable to hold a single byte of the file data
            int i = 0;

            // A counter to print a new line every 16 bytes read.
            int cnt = 0;

            // Read till the end of the file and print the byte into Hexadecimal 
            // value.
            while ((i = fis.read()) != -1) {
                if (i != -1) {
                    System.out.printf("%02X ", i);
                    cnt++;
                }

                if (cnt == 16) {
                    System.out.println("");
                    cnt = 0;
                }
            }
        } catch (FileNotFoundException e) {
			e.printStackTrace();
		} finally {
            fis.close();
        }
	}
}

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.