3

我正在尝试从文件(签名)中读取最后 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);
4

2 回答 2

3

我会使用 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();
于 2013-04-26T02:41:01.750 回答
1

我认为您对读取方法参数感到困惑..

    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.

希望这可以帮助!

于 2013-04-26T02:51:36.473 回答