【问题标题】:How to read and write an object to a text file in java?如何在java中读取对象并将其写入文本文件?
【发布时间】:2015-05-23 13:24:22
【问题描述】:

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

反序列化不起作用:

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

【问题讨论】:

  • 阅读序列化并申请 ..
  • 读取文件有问题。写作工作。
  • 您肯定可以比“不工作”更具体吗?是否抛出异常?如果是这样,堆栈跟踪是什么?
  • try catch 中抛出异常,我在注释中写了异常,见行后。
  • 将数组包裹在另一个对象中

标签: java object serialization file-io deserialization


【解决方案1】:

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

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

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

您可以使用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 可以以类似的方式用于从文件中读回数组。

【讨论】:

    【解决方案2】:

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

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

    (另见best practices。)

    【讨论】:

    • 我得到 endofile 异常和空指针异常 ObjectInputStream input = null; input = new ObjectInputStream(new FileInputStream("myfile.txt")); // 此处文件结束 array = (players[]) input.readObject(); // 这里是空指针,这里有什么问题
    • cmets 中的代码不太清晰。考虑将其编辑到您的问题中,或在适当的情况下提出新问题。
    猜你喜欢
    • 1970-01-01
    • 2021-12-12
    • 1970-01-01
    • 2016-12-06
    • 2017-10-18
    • 1970-01-01
    • 2013-09-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多