Saturday, May 31, 2025

[JAVA] READ HEX from File

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

public class HexFileReader {

    public static byte[] readFileBytes(String filePath) throws IOException {
        FileInputStream fis = new FileInputStream(filePath);
        byte[] fileBytes = fis.readAllBytes();
        fis.close();
        return fileBytes;
    }

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

    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt"; // Replace with your file path
        try {
            byte[] fileBytes = readFileBytes(filePath);
            String hexString = bytesToHex(fileBytes);
            System.out.println("Hexadecimal representation:\n" + hexString);
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

No comments: