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) 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
来源:https://stackoverflow.com/questions/4074667/how-to-read-content-of-exe-file-in-java