List<Map<String,Object>>转byte[]后转回仅得首个对象,如何解决?
I get it, that frustrating moment when serialization works one way but not the other! Let's break down what's going wrong and fix it.
First off, the available() method on ObjectInputStream isn't meant to tell you if there are more objects to read. It only returns the number of bytes that can be read right now without blocking—this doesn't correlate to how many serialized objects are left in the stream. That's why it's always returning 0 for you, even when there's more data to process.
The Cleanest Fix: Serialize the Entire List as One Object
The best practice here is to write the entire List<Map<String,Object>> as a single serialized object, instead of handling each map individually. This way, reading it back is a one-step process that gives you the full list immediately.
Writing the List to Byte Array
List<Map<String, Object>> yourDataList = ...; // Your populated list try (ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(baos)) { oos.writeObject(yourDataList); // Write the entire list in one go byte[] serializedBytes = baos.toByteArray(); // Use or store serializedBytes as needed } catch (IOException e) { e.printStackTrace(); }
Reading the Byte Array Back to List
byte[] serializedBytes = ...; // Your byte array from serialization try (ByteArrayInputStream bais = new ByteArrayInputStream(serializedBytes); ObjectInputStream ois = new ObjectInputStream(bais)) { // Cast the read object back to your list type @SuppressWarnings("unchecked") List<Map<String, Object>> restoredList = (List<Map<String, Object>>) ois.readObject(); // Now you have the complete list with all maps! } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); }
If You Serialized Each Map Individually
If you previously wrote each map in the list separately (looping through and calling writeObject() on each map), you'll need to read until you hit an EOFException—this is the standard way to detect the end of the object stream.
byte[] serializedBytes = ...; List<Map<String, Object>> restoredList = new ArrayList<>(); try (ByteArrayInputStream bais = new ByteArrayInputStream(serializedBytes); ObjectInputStream ois = new ObjectInputStream(bais)) { while (true) { try { @SuppressWarnings("unchecked") Map<String, Object> map = (Map<String, Object>) ois.readObject(); restoredList.add(map); } catch (EOFException e) { break; // No more objects to read } } } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); }
Important Note
Make sure every object in your maps (including any custom classes you're using as keys or values) implements the Serializable interface. If any object isn't serializable, the serialization/deserialization process will throw an exception.
内容的提问来源于stack exchange,提问作者Aniket Kulkarni

