gpt4 book ai didi

java - FileInputStream 读取文件的最后 128 个字节

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:18:20 26 4
gpt4 key购买 nike

我正在尝试从文件(签名)读取最后 128 个字节,然后尝试读取直到这些字节,但第一部分(读取最后 128 个字节)返回 ArrayIndexOutOfBoundsException:

byte[] signature = new byte[128];


FileInputStream sigFis = new FileInputStream(f);
sigFis.read(signature, (int)f.length()-128, 128);
sigFis.close();

然后最后一部分似乎也不起作用,我正在使用逐渐增加的偏移量:

        CipherInputStream cis = new CipherInputStream(fis, c);
FileOutputStream fos = new FileOutputStream(destFile);
int i = cis.read(data);
int offset = 0, maxsize = (int)f.length()-128;

while((i != -1) && offset<maxsize){
fos.write(data, 0, i);
sig.update(data);
fos.flush();
i = cis.read(data);
offset+=1024;
}

我在执行操作时收到了英国皇家空军的 EOFExcpetion...

byte[] signature = new byte[128];


int offset = (int)f.length()-128;

raf.seek(offset);

raf.readFully(signature, 0, 128);

最佳答案

我会使用 File 或 FileChannel 来获取文件大小。这是读取到最后 128 个字节的方法

    FileInputStream is = new FileInputStream("1.txt");
FileChannel ch = is.getChannel();
long len = ch.size() - 128;
BufferedInputStream bis = new BufferedInputStream(is);
for(long i = 0; i < len; i++) {
int b = bis.read();
...
}

如果我们继续阅读,我们将得到最后的 128 个字节

              ByteArrayOutputStream bout128 = new ByteArrayOutputStream();
for(int b; (b=bis.read() != -1);) {
bout128.write(b);
}
byte[] last128 = bout128.toByteArray();

关于java - FileInputStream 读取文件的最后 128 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16227092/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com