Java FileInputStream读取到文件的最后128字节
我尝试从文件(签名)中读取最后128个字节,然后尝试读取这些字节,但第一部分(读取最后128个字节)返回ArrayIndexOutOfBoundsException:Java FileInputStream读取到文件的最后128字节,java,fileinputstream,Java,Fileinputstream,我尝试从文件(签名)中读取最后128个字节,然后尝试读取这些字节,但第一部分(读取最后128个字节)返回ArrayIndexOutOfBoundsException: byte[] signature = new byte[128]; FileInputStream sigFis = new FileInputStream(f); sigFis.read(signature, (int)f.length()-128, 128); sigFis.
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;
}
我会使用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();
...
}
ByteArrayOutputStream bout128 = new ByteArrayOutputStream();
for(int b; (b=bis.read() != -1);) {
bout128.write(b);
}
byte[] last128 = bout128.toByteArray();
我认为您对read方法参数感到困惑
FileInputStream sigFis = new FileInputStream(f);
sigFis.read(signature, (int)f.length()-128, 128);
//This doesn't give you last 128 bits.
// The offset is offset of the byte array 'signature
// Thats the reason you see ArrayIndexOutOfBoundsException
sigFis.close();
将read()方法替换为
sigFis.read(signature);
//But now signature cannot be just 128 array but length of file. And read the last 128 bytes
InputStream读取方法签名如下所示:
int java.io.FileInputStream.read(byte[] b, int off, int len)
Parameters:
b the buffer into which the data is read.
off the start offset in the destination array b
len the maximum number of bytes read.
希望这有帮助 这很有帮助,而且很多,我犯了一个多么愚蠢的错误,这就是你没有用propper的注意力阅读方法属性所得到的。。。谢谢。我将使用RandomAccessFile,因为我还想将其修剪为特定大小以删除签名,因此,我可以跳过(file.length()-128),然后读取(数据)。谢谢,这很有意义,我会尝试一下,但我想我将使用RandomAccessFile,然后跳过字节,读取最后的128。对不起,这件事很特别,流的这种使用会不会改变我的FileInputStream的指针(或者你是说我应该创建一个新的流?),从而破坏数据的写入?如果你只想从文件中读取,那么使用FileInputStream更符合逻辑。至于RandomAccessFile,如果您更改文件位置然后写入,它将从新位置写入。您所说的“使用FileInputStream更符合逻辑”是什么意思?因为这正是我试图找到的,读取文件,但在流/文件上剩余128字节时停止它。请您帮助读取,直到最后128字节,但使用fileinputstream?我使用的该死的randomAccessFile仍然有问题,我进行搜索(file.length()-128),然后读取(data,0,128)它只是发送了一个EOFEException…我犯了一个愚蠢的错误,我在读一个空文件。。。
int java.io.FileInputStream.read(byte[] b, int off, int len)
Parameters:
b the buffer into which the data is read.
off the start offset in the destination array b
len the maximum number of bytes read.