Java display file content in hexadecimal format


 

Java display file content in hexadecimal format

In this section, you will learn how to read the file content and display it in hexadecimal format.

In this section, you will learn how to read the file content and display it in hexadecimal format.

Java display file content in hexadecimal format

In this section, you will learn how to read the file content and display it in hexadecimal format.

Reading a file is a common task but here we are going to display the file data in hexadecimal format. For this we have used FileInputStream class to open a file and initialized a variable to hold a single byte of the file data. Then we have read the file contents byte by byte and print the value in hexadecimal format. If you want to process the file faster then you may read the file contents into some array of bytes.

Here is the code:

import java.io.*;

public class FileInHexadecimal {
	public static void main(String[] args) throws Exception {
		FileInputStream fis = new FileInputStream("C:/data.txt");
		int i = 0;
		while ((i = fis.read()) != -1) {
			if (i != -1) {
				System.out.printf("%02X ", i);
			}
		}
		fis.close();
	}
}

Ads