Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
290 views
in Technique[技术] by (71.8m points)

java - ObjectInputStream happy with FileInputStream, not happy with 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();
  }

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");

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)

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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 can be a suspect, especially its resource filtering feature.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...