2

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

BufferInputStream.read(byteArray, 8170, 22);

java正在引发异常,说它是封闭的流。在这方面的任何帮助将不胜感激。谢谢。

4

3 回答 3

5

I haven't tried this, but I suppose you could use a MappedByteBuffer to read just the last 22 bytes.

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

Then simply flush your buffer into an array and that's it.

byte[] payload = new byte[22];
buffer.get(payload);
于 2015-11-25T12:25:44.647 回答
0

您首先需要从文件中创建一个 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();
}
于 2015-11-25T12:14:36.627 回答
-1

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

    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);
于 2015-11-25T12:30:12.963 回答