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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30413227/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 17:04:58  来源:igfitidea点击:

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

javaobjectserializationfile-iodeserialization

提问by Sam

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

回答by Mohammad Jafar Mashhadi

The process of converting objects into strings and vice versa is called Serialization and Deserialization. In order to serialize an object it should implement Serializableinterface. Most built-in data types and data structures are serializable by default, only certain classes are not serializable (for example Socketis not serializable).

将对象与字符串相互转换的过程称为序列化和反序列化。为了序列化一个对象,它应该实现Serializable接口。大多数内置数据类型和数据结构默认是可序列化的,只有某些类不可序列化(例如Socket不可序列化)。

So first of all you should make your class Serializable:

所以首先你应该让你的类可序列化:

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

The you can use ObjectOutputStreamto 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();
    }
}

ObjectInputStreamcan be used in a similar way to read the array back from file.

ObjectInputStream可以以类似的方式用于从文件中读回数组。

回答by das-g

As far as I know, Java doesn't give you an easy way to do this for arbitrary objects. Thus, consider restricting yourself to an array of Serializable.

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

If the objects you have to handle are of your own classes and you thus want these classes to implement the java.io.Serializableinterface, 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. (So if your classes implement Serializablewithout completely following the conditions it poses, you might get runtime errors or just 'wrong' and maybe hard-to-detect runtime behavior.)

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

(See also these best practices.)

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