How to read content of .EXE file in Java

南笙酒味 提交于 2019-12-06 08:05:15

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();
  }

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.

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();
}

Java's Integer class can convert from binary to hexadecimal string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!