FileInputStream读取直到最后128个字节的文件

时间:2013-04-26 00:55:47

标签: java fileinputstream

我正在尝试从文件中读取最后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;
        }

我得到了我用来做我的操作的RAF的EOFExcpetion ...

byte[] signature = new byte[128];


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

            raf.seek(offset);       

            raf.readFully(signature, 0, 128);

2 个答案:

答案 0 :(得分: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();

答案 1 :(得分:1)

我认为你对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.

希望这有帮助!