简体   繁体   English

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

[英]How to read and write an object to a text file in java?

I have an array of objects and I want to write them in a text file. 我有一个对象数组,我想在文本文件中写它们。 So that I can later read the objects back in an array. 这样我以后就可以在数组中读回对象了。 How should I do it? 我该怎么办? Using Serialization. 使用序列化。

Deserialization is not working: 反序列化不起作用:

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();
    }

The process of converting objects into strings and vice versa is called Serialization and Deserialization. 将对象转换为字符串(反之亦然)的过程称为序列化和反序列化。 In order to serialize an object it should implement Serializable interface. 为了序列化对象,它应该实现Serializable接口。 Most built-in data types and data structures are serializable by default, only certain classes are not serializable (for example Socket is not serializable). 大多数内置数据类型和数据结构默认是可序列化的,只有某些类不可序列化(例如Socket不可序列化)。

So first of all you should make your class Serializable: 首先,你应该使你的类Serializable:

 class Student implements java.io.Serializable {
     String name;
     String studentId;
     float gpa;
     transient String thisFieldWontBeSerialized;
 }

The you can use ObjectOutputStream to serialize it and write to a file: 您可以使用ObjectOutputStream进行序列化并写入文件:

public class Writer {
    static void writeToFile(String fileName, Student[] students) throws IOException {
        File f = new File(fileName);
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(f));
        oos.writeObject(students);
        oos.flush();
        oos.close();
    }
}

ObjectInputStream can be used in a similar way to read the array back from file. 可以以类似的方式使用ObjectInputStream从文件中读取数组。

As far as I know, Java doesn't give you an easy way to do this for arbitrary objects. 据我所知,Java并没有为您提供一种简单的方法来为任意对象执行此操作。 Thus, consider restricting yourself to an array of Serializable . 因此,请考虑将自己限制为Serializable数组。

If the objects you have to handle are of your own classes and you thus want these classes to implement the java.io.Serializable interface, carefully read what 'contract' it comes with , as not all of what you have to guarantee for your class will be enforced programatically at compile-time. 如果您必须处理的对象属于您自己的类,并且您希望这些类实现java.io.Serializable接口,请仔细阅读它所附带的“契约” ,而不是您必须为类保证的所有内容将在编译时以编程方式强制执行。 (So if your classes implement Serializable without completely following the conditions it poses, you might get runtime errors or just 'wrong' and maybe hard-to-detect runtime behavior.) (因此,如果您的类在没有完全遵循它所带来的条件的情况下实现Serializable ,您可能会遇到运行时错误或者只是'错误'并且可能难以检测运行时行为。)

(See also these best practices .) (另见这些最佳实践 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM