Saturday, May 31, 2025

[JAVA] HEX from File

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import org.apache.commons.codec.binary.Hex;

public class HexFileUtil {

    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt";

        try {
            // Example 1: Read and convert hex string to byte array
            String hexString = Files.readString(Paths.get(filePath)).trim();
            byte[] byteArray = hexStringToByteArray(hexString);
            System.out.println("Byte array from hex string: " + java.util.Arrays.toString(byteArray));

            // Example 2: Read file as bytes and convert to hex string
            byte[] fileBytes = Files.readAllBytes(Paths.get(filePath));
            String hexStringFromFile = byteArrayToHexString(fileBytes);
            System.out.println("Hex string from file bytes: " + hexStringFromFile);


             // Example 3: Read file as bytes and convert to hex string using Apache Commons Codec
             byte[] fileBytes2 = Files.readAllBytes(Paths.get(filePath));
             String hexStringFromBytes = Hex.encodeHexString(fileBytes2);
             System.out.println("Hex string from file bytes using Apache Commons Codec: " + hexStringFromBytes);


            // Example 4: Read file and print it in hex representation using FileInputStream

            printHexStream(new FileInputStream(filePath), 16);

        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }


    public static void printHexStream(final FileInputStream inputStream, final int numberOfColumns) throws IOException{
         long streamPtr=0;
         while (inputStream.available() > 0) {
             final long col = streamPtr++ % numberOfColumns;
             System.out.printf("%02x ",inputStream.read());
             if (col == (numberOfColumns-1)) {
                 System.out.printf("\n");
             }
         }
    }

    public static byte[] hexStringToByteArray(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                                 + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    public static String byteArrayToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bytes) {
            sb.append(String.format("%02x", b));
        }
        return sb.toString();
    }
}

No comments: