【问题标题】:Error: Exception in thread AWT-EventQueue-0 java.lang.ClassCastException [closed]错误:线程 AWT-EventQueue-0 java.lang.ClassCastException 中的异常 [关闭]
【发布时间】:2021-05-26 03:58:39
【问题描述】:

是否可以从单个文件中读取不同类型的对象?

【问题讨论】:

标签: java exception serialization io classcastexception


【解决方案1】:

是否可以从单个文件中读取不同类型的对象..?

当然是!这是证明的输出:

Object: 42                                           // Integer
Object: The quick brown fox jumps over the lazy dog  // String
Object: 42.001                                       // Double

这是用于上述输出的源代码:

public class ObjectSerialization {

    public static void main(String[] args) throws IOException, ClassNotFoundException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(baos);
        oos.writeObject(new Integer(42));
        oos.writeObject("The quick brown fox jumps over the lazy dog");
        oos.writeObject(new Double(42.001));
        
        oos.flush();
        oos.close();
        
        ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bais);
        Object o;
        o = ois.readObject();
        System.out.println("Object: " + o);
        o = ois.readObject();
        System.out.println("Object: " + o);
        o = ois.readObject();
        System.out.println("Object: " + o);
    }
}

敏锐的人可能会注意到示例中没有涉及File,但可以随意调整代码以使用实际文件来确认它有效。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多