如何在Java中将对象读取和写入文本文件? [英] How to read and write an object to a text file in java?

查看:140
本文介绍了如何在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.

反序列化无效:

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


推荐答案

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

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. Most built-in data types and data structures are serializable by default, only certain classes are not serializable (for example Socket is not serializable).

因此,首先您应该使您的类可序列化:

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

您可以使用 ObjectOutputStream 对其进行序列化并写入文件:

The you can use ObjectOutputStream to serialize it and write to a file:

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 可以类似的方式从文件中读取数组。

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

这篇关于如何在Java中将对象读取和写入文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆