【问题标题】:weird IO operation behavior in jar filejar 文件中奇怪的 IO 操作行为
【发布时间】:2013-12-10 08:56:10
【问题描述】:

好吧,我刚刚发布了一个(半类似的)问题here,我问了这个问题,但我遇到了问题,这是一个 IO 问题。

在我们的程序中,我们必须读取一个文件(大约 10MB)并对其进行解密,我正在使用以下类。

class FileStream extends InputStream {
  public int available() throws IOException {
    return baseStream.available();
  }
  public boolean markSupported() {
    return false;
  }
  InputStream baseStream;
  byte[] data = new byte[1048576];
  int loopRead = 0;
  int streamSize;
  int dataRead;
  public FileStream(InputStream is) throws Exception {
    this.baseStream = is;
    streamSize = is.available();
  }
  public int read() {
    if (dataRead == streamSize) {
      return -1;/* End of the stream */
    }
    dataRead++;
    if (loopRead == data.length) {
      decrypt();
    }
    return data[loopRead++];
  }
  byte[] tempRead = new byte[4096];// block(smallest) decryption size
  void decrypt() {
    try {
      int r;
      for (int i = 0; i < (data.length / tempRead.length); i++) {
        System.out.print("Data Available: "+baseStream.available());
        r = baseStream.read(tempRead);// read from base stream, ERROR IS HERE!
        System.out.print("Data read: "+r);//not always 4096 in jar file, vary numbers!
        if (r <= 0) {
          return;
        }
        System.arraycopy(tempRead, 0, data, (i * tempRead.length),
            tempRead.length);
      }// end-for
      // /////decrypt the data////////
      loopRead = 0;
    } catch (Exception ex) {
    }
  }
}

WORKS 当我从 eclipse 运行它时,但是当我生成 JAR 文件(导出)并从命令行 (java -Xmx1280M -jar app.jar) 运行它时,它不会读取数据正确。

块大小(crypt block size)是4096,所以文件大小可以被4096整除,真不知道为什么会这样!它应该每次读取 4096 字节的数据,但它不会,并且数据可用性总是超过 4096(应该是)。

请帮忙,这里可能会出现什么错误或情况?!

提前致谢。

【问题讨论】:

  • 运行时会发生什么?如果您不这样做,它可能会有所帮助;不仅仅是在解密方法中吞下异常。将 x.printStackTrace() 放入 catch 块中,重新构建,运行运行,看看您是否从中得到任何帮助
  • 亲爱的也不例外,它只是不会在每次调用中读取4096 字节。 @DaveHowes
  • 这不是奇怪的行为。这正是定义的行为。您只是假设如果它在 Eclipse 中以这种方式工作,那么它在其他任何地方都会以相同的方式工作。

标签: java eclipse io


【解决方案1】:

这是基本的 IO。 InputStreamread(byte[]) 方法不能保证读取整个字节数组的数据。这就是它返回实际读取的字节数的原因。

DataInputStream 确实有一个 readFully() 方法可以完全填充数组。

【讨论】:

  • 那么为什么当我从 Eclipse 运行它时它可以毫无问题地工作呢?为什么数据可用性总是比请求读取的多?
  • 因为。这就是为什么。 read(byte[]) 的合约定义它最多可以读取 byte[].length 个字节,您需要进行相应的编码。如果您忽略定义,您将遇到类似于您当前所处的情况。它是否在 eclipse 中工作并不重要,它不能保证在任何地方都可以按照您的编码方式工作。
  • 谢谢哥们,你是王者 :)
猜你喜欢
  • 2017-07-27
  • 1970-01-01
  • 2013-03-15
  • 2018-04-22
  • 1970-01-01
  • 2020-06-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多