Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Type cast InputStream to ObjectInputStream

Tags:

java

android

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?

like image 620
MaxGyver Avatar asked May 05 '26 18:05

MaxGyver


1 Answers

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();
like image 143
Luiggi Mendoza Avatar answered May 08 '26 09:05

Luiggi Mendoza



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!