ObjectInputStream对FileInputStream很满意,对getResourceAsStream不满意 [英] ObjectInputStream happy with FileInputStream, not happy with getResourceAsStream

查看:107
本文介绍了ObjectInputStream对FileInputStream很满意,对getResourceAsStream不满意的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些非常标准的代码,它从流中获取序列化对象,基本上看起来像这样:

I have some pretty standard code which takes in a serialized object from a stream, which bascially looks like this:


  Object getObjectFromStream(InputStream is) {
    ObjectInputStream ois = new ObjectInputStream(is);
    return ois.readObject();
  }

然后我的资源文件夹中有一个文件,所以在我的开发机器上,我可以将它作为一个引用文件,或作为JarResource:

I then have a file in my resources folder, so on my development machine, I can either reference it as a File, or as a JarResource:


  InputStream is = new FileInputStream("/home/.../src/main/resources/serializedObjects/testObject");
  InputStream is = this.getClass().getResourceAsStream("/serializedObjects/testObject");

在我看来,两者都应该做同样的事情。但是,它会解析为有效(非空)流,但FileInputStream正确地从我的getObjectFromStream(InputStream)方法返回一个Object,而getResourceAsStream版本抛出此异常:

In my head, both should do the exact same thing. As it happens however, both resolve to a valid (non-null) stream, but the FileInputStream correctly returns an Object from my getObjectFromStream(InputStream) method, while the getResourceAsStream version throws this exception:


  java.io.StreamCorruptedException: invalid stream header: EFBFBDEF
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:800)
    at java.io.ObjectInputStream.(ObjectInputStream.java:297)

大多数情况下,我想知道如何解决这个问题,但我也很感激了解两个InputStream之间的区别......

Mostly, I would like to know how to fix this, but I'd also appreciate an understanding of the difference between the two InputStreams ...

推荐答案

EFBFBD 是Unicode替换字符U + FFFD的UTF-8表示。所以,看起来文件是通过一些编码转换过程传递的。

EFBFBD is a UTF-8 representation of Unicode replacement character U+FFFD. So, it looks like file was passed through some encoding conversion process.

Maven可能是一个嫌疑人,尤其是它的资源过滤功能。

Maven can be a suspect, especially its resource filtering feature.

这篇关于ObjectInputStream对FileInputStream很满意,对getResourceAsStream不满意的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆