Java中读取可执行文件的可能选项和最适合的方法。
我想生成一个.exe文件的十六进制表示。我考虑先以二进制形式读取文件,然后进行转换。但是如何读取.exe文件呢?
Java中读取可执行文件的可能选项和最适合的方法。
我想生成一个.exe文件的十六进制表示。我考虑先以二进制形式读取文件,然后进行转换。但是如何读取.exe文件呢?
1)以字节形式读取文件。使用
BufferedInputStream( new FileInputStream( new File("bin.exe") ) )
2)将每个字节转换为十六进制格式。
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();
}
编辑
我没有想到你需要它作为字符串。修改了示例以实现此目的。这样做应该比使用BufferedReader
性能略好,因为我们自己进行缓冲。
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();
}
InputStream
是 Java 中用于读取二进制文件的主要类。您可以使用 FileInputStream
从文件中读取字节。然后,您可以使用 read()
方法读取每个字节,并将该字节显示为两个十六进制字符。