How to read content of .EXE file in Java

匆匆过客 提交于 2019-12-22 17:39:18

问题


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?


回答1:


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



回答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.




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



回答4:


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



来源:https://stackoverflow.com/questions/4074667/how-to-read-content-of-exe-file-in-java

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