In this article, we will learn how to convert a file content to Hexadecimal (hex). First, we read the file contents byte by byte and then print the value in hexadecimal format. As an alternative to read a single byte we can read the file contents into array of bytes at once to process the file faster.
1. Java Convert File Content to Hexadecimal (Hex)
Here in the below java code, we are reading the file into an InputStream
and using String.format(%X)
to convert each byte into a hex code.
Below java code shows how to convert and display file contents into hex format –
package com.kodehelp.java.io;
import java.io.FileInputStream;
import java.io.IOException;
public class FileContentToHexadecimal {
public static void main(String[] args) throws IOException {
// Open the file using FileInputStream
try (FileInputStream fis = new FileInputStream("kodehelp.txt")) {
// 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 in hexadecimal
// valueS.
while ((i = fis.read()) != -1) {
System.out.printf("%02X ", i);
cnt++;
if (cnt == 16) {
System.out.println("");
cnt = 0;
}
}
}
}
}
OUTPUT
54 68 69 73 20 69 73 20 74 68 65 20 53 61 6D 70
6C 65 20 66 69 6C 65 2E %