如何在java中读取和写入对象到文本文件?

Sam*_*Sam 5 java file-io serialization object deserialization

我有一个对象数组,我想将它们写入文本文件中。这样我以后就可以读回数组中的对象。我该怎么做? 使用序列化。

反序列化不起作用:

public static void readdata(){
        ObjectInputStream input = null;
        try {
            input = new ObjectInputStream(new FileInputStream("myfile.txt")); // getting end of file exception here
        } catch (FileNotFoundException e1) {
            e1.printStackTrace();
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        try {
            array = (players[]) input.readObject(); // null pointer exception here
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        readdata();
        writedata();
    }
Run Code Online (Sandbox Code Playgroud)

das*_*s-g 0

据我所知,Java 并没有提供一种简单的方法来对任意对象执行此操作。因此,请考虑将自己限制在Serializable.

如果您必须处理的对象属于您自己的类,因此您希望这些类实现接口java.io.Serializable,请仔细阅读它附带的“契约”,因为并非您必须为您的类保证的所有内容都会以编程方式强制执行编译时。(因此,如果您的类Serializable在没有完全遵循它所提出的条件的情况下实现,您可能会遇到运行时错误或只是“错误”,并且可能难以检测运行时行为。)

(另请参阅这些最佳实践。)