In this example we will show how to write a class to a file and read it in Java.
Source Code
1)Create a new class Student
package com.beginner.examples;
import java.io.Serializable;
public class Student implements Serializable {
private String name;
private static final long serialVersionUID = 1 L;
private int age;
public Student() {}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String toString() {
return "Name: " + this.name + "nAge: " + this.age;
}
}
2)
package com.beginner.examples;
import java.io.File;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
public class WriteObjectToFileExample {
/**
* @param args
*/
public static void main(String[] args) {
Student stu = new Student("Tom", 20);
try {
FileOutputStream fos = new FileOutputStream(new File("MyText.txt"));
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(stu);
fos.close();
oos.close();
FileInputStream fis = new FileInputStream(new File("MyText.txt"));
ObjectInputStream ois = new ObjectInputStream(fis);
Student s = (Student) ois.readObject();
System.out.println(s.toString());
} catch (IOException e) {
// TODO: handle exception
System.out.println(e.toString());
} catch (Exception e) {
// TODO: handle exception
}
}
}
Output:
Name: Tom
Age: 20
##3.Tipe
it is mandatory that the concerned class implements Serializable interface
References
Imported packages in Java documentation: