简体   繁体   中英

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

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 can be used in a similar way to read the array back from file.

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 .

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. (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.)

(See also these best practices .)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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