MaxGyver
MaxGyver

Reputation: 437

Type cast InputStream to ObjectInputStream

I have written a byte[][][][] object to a file using this code:

byte[][][][] allMaps = new byte[10][8][][];
allMaps = ...;
ObjectOutputStream outputStream = null;
  try {
        outputStream = new ObjectOutputStream(new FileOutputStream("all_maps"));
        outputStream.writeObject(allMaps);
      } catch (IOException e) {
       ...
      }

Now I'm trying to read that byte[][][][] object into my Android app:

InputStream inputStream = getResources().openRawResource(
            getResources().getIdentifier("raw/all_maps", "raw", getPackageName()) );
    try {
        byteMaps = (byte[][][][]) ((ObjectInputStream) inputStream).readObject();
    } catch (OptionalDataException e) {
        ...

But then I get this error (in the line starting with "byteMaps"):

java.lang.ClassCastException: android.content.res.AssetManager$AssetInputStream cannot be cast to java.io.ObjectInputStream

Why is inputStream of the type AssetInputStream and not java.io.InputStream?

Upvotes: 3

Views: 6376

Answers (2)

Rahul Winner
Rahul Winner

Reputation: 430

You would need to create object of ObjectInputStream with 'inputStream'.. Pass inputStream as an arguments to the constructor of ObjectInputStream. Then call readObject() on objectInputStream object.. Hope it helps.


Upvotes: 3

Luiggi Mendoza
Luiggi Mendoza

Reputation: 85779

You usually don't type cast streams but wrap (decorate) them with a proper Input/Output stream class to read the content of the stream in an easier way. Here, you have to replace this:

byteMaps = (byte[][][][]) ((ObjectInputStream) inputStream).readObject();

into:

ObjectInputStream oos = new ObjectInputStream(inputStream);
try {
    byteMaps = (byte[][][][]) oos.readObject();

Upvotes: 4

Related Questions