如何获取 java 中 .exe 文件的最后 'n' 个字节?

How to get last 'n' bytes of .exe file in java?

我需要在 java 中的自解压 .exe 文件中获取最后 22 个字节作为中央目录的末尾(没有命令行,请没有终端解决方案)。我尝试使用 bufferInputStream 读取 .exe 文件的内容并获得成功但是当尝试使用

获取最后 22 个字节时
BufferInputStream.read(byteArray, 8170, 22);

java 正在引发异常,说它已关闭 stream.Any 在这方面的帮助将不胜感激。谢谢

您首先需要从文件创建一个 FileInputStream。

File exeFile = new File("path/to/your/exe");
long size = exeFile.length();
int readSize = 22;
try {
    FileInputStream stream = new FileInputStream(exeFile);
    stream.skip(size - readSize);
    byte[] buffer = new byte[readSize];
    if(stream.read(buffer) > 0) {
        // process your data
    }
    else {
        // Some errors
    }
    stream.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

我没试过这个,但我想你可以使用 MappedByteBuffer 只读取最后 22 个字节。

File file = new File("/path/to/my/file.bin");

long size = file.length();
FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ);
MappedByteBuffer buffer = channel.map(MapMode.READ_ONLY, size-22, 22);

然后只需将缓冲区刷新到数组中即可。

byte[] payload = new byte[22];
buffer.get(payload);

给出 java.io.IOException 的代码示例:流已关闭 您必须先检查输入流

    InputStream fis = new FileInputStream("c:/myfile.exe");
    fis.close(); // only for demonstrating

    // correct but useless
     BufferedInputStream bis = new BufferedInputStream(fis);        

    byte x[]=new byte[100];

    // EXCEPTION: HERE: if fis closed
    bis.read(x,10,10);