3

What are the possible options and the most appropiate for reading an executable file in Java.

I want produce the hexadecimal representation of an .exe file. Im thinking of reading the file in binary and then doing the conversion. But how can i read the .exe?

Carlos
  • 5,405
  • 21
  • 68
  • 114
  • 1
    Not sure I follow. You want to reproduce the functionality of a standard hex editor? – Kirk Woll Nov 02 '10 at 03:13
  • @Kirk: well not really, this question is linked to http://stackoverflow.com/questions/4068218/programmatical-approach-in-java-for-file-comparison. – Carlos Nov 02 '10 at 03:18

3 Answers3

6

1) read the file in as bytes. use


   BufferedInputStream( new FileInputStream( new File("bin.exe") ) )

2) convert each byte to hex format.


    static final String HEXES = "0123456789ABCDEF";
  public static String getHex( byte [] raw ) {
    if ( raw == null ) {
      return null;
    }
    final StringBuilder hex = new StringBuilder( 2 * raw.length );
    for ( final byte b : raw ) {
      hex.append(HEXES.charAt((b & 0xF0) >> 4))
         .append(HEXES.charAt((b & 0x0F)));
    }
    return hex.toString();
  }
smartnut007
  • 6,324
  • 6
  • 45
  • 52
  • thanks so much buddy, more than anything i was wanted to know if java could handle executables, which is now clear. Thanks for going that extra mile. – Carlos Nov 02 '10 at 03:25
  • Every programming language should be able to handle binary format. Think of it this way. Everything is represented in binary form. 0s and 1s. So, one can safely assume that a programming language can read in 0s and 1s and transform them into something simple like hex. – smartnut007 Nov 02 '10 at 12:02
3

Edit
It didn't occur to me that you'd want it as a string. Modified the example to do so. It should perform slightly better than using a BufferedReader since we're doing the buffering ourselves.

public String binaryFileToHexString(final String path)
    throws FileNotFoundException, IOException
{
    final int bufferSize = 512;
    final byte[] buffer = new byte[bufferSize];
    final StringBuilder sb = new StringBuilder();

    // open the file
    FileInputStream stream = new FileInputStream(path);
    int bytesRead;

    // read a block
    while ((bytesRead = stream.read(buffer)) > 0)
    {
        // append the block as hex
        for (int i = 0; i < bytesRead; i++)
        {
            sb.append(String.format("%02X", buffer[i]));
        }
    }
    stream.close();

    return sb.toString();
}
Jeff Mercado
  • 129,526
  • 32
  • 251
  • 272
2

An InputStream in Java is the primary class for reading binary files. You can use a FileInputStream to read bytes from a file. You could then read in each byte with the read() method and display that byte as 2 hex characters if you wanted.

Pace
  • 41,875
  • 13
  • 113
  • 156