【问题标题】:Java Inputstream not read entirelyJava Inputstream 未完全读取
【发布时间】:2014-07-01 13:23:43
【问题描述】:

我有一个图片流(目前是一个 png,但它可能是其他东西),我想将它转换为一个文件。 问题:未完全读取流: 流来的初始图片20KB左右,压轴文件16B 这是我的代码:

...
    fileImageOutput = new FileImageOutputStream(_templateFile);        

    int read = 0;
    byte[] bytes = new byte[1024];

    while ((read = imageStream.read(bytes)) != -1) {
        fileImageOutput.write(bytes, 0, read);
    }
}
catch(IOException ioe)
{
    throw ioe;
}
finally
{
    if(fileImageOutput!=null)
        fileImageOutput.close();
    if(imageStream!=null)
        imageStream.close();
}

非常感谢您的帮助。

尼古拉斯

【问题讨论】:

  • 你能在你创建输入流的地方插入代码吗?你也做过任何检查,看看这 16 个字节是什么,看看它们是否与图像文件的前 16 个字节对齐?
  • 先读取文件内容并在屏幕上打印并打开使用的文件检查内容差异
  • 在关闭流之前调用flush
  • @Stefoan close flushes too
  • 您的 imageStream 有问题。你能告诉我们更多关于它的信息吗?会不会是填充它的任何来源都是未正确刷新的来源?

标签: java image file inputstream


【解决方案1】:

当您写入文件时,您应该使用 FileOutputStream 而不是 FileImageOutputStream.. 写入器写入字节,无论它们是什么。如果我们在您的 try/catch 块中看到整个代码,那就更清楚了。

...
BufferedWriter writer = new BufferedWriter(new FileOutputStream(_templateFile));    
int read;
while ((read = imageStream.read()) != -1) {
  writer.write(read);
}
...

【讨论】:

    【解决方案2】:

    感谢您的回答。 实际上,我发现了问题:我混合了两种加载图片的方式,并且都使用了输入流。由于我从第一个开始,我假设这改变了它的索引,并且流的第二次读取从最后开始。无论如何,我删除了第二次阅读,现在可以使用了!

    谢谢

    尼可

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-03
      • 2010-10-11
      • 2016-04-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-26
      相关资源
      最近更新 更多