Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
    }
like image 671
Sam Avatar asked Oct 19 '22 11:10

Sam


1 Answers

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.

like image 110
Mohammad Jafar Mashhadi Avatar answered Oct 22 '22 02:10

Mohammad Jafar Mashhadi