In Java object can be read or written to a file using serialization and deserialization.
Example:import java.io.*;
public class ObjectFileExample {
public static void main(String[] args) {
// Create an object to write to file
User objectToWrite = new User("Mike", 32);
// Write object to file
writeObjectToFile(objectToWrite, "object.txt");
// Read object from file
User objectFromFile = readObjectFromFile("object.txt");
System.out.println(STR."Object read from file: \{objectFromFile}");
}
// Method to write object to file
public static void writeObjectToFile(Object obj, String fileName) {
try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream(fileName))) {
oos.writeObject(obj);
System.out.println("Object successfully written to file.");
} catch (IOException e) {
e.printStackTrace();
}
}
// Method to read object from file
public static User readObjectFromFile(String fileName) {
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(fileName))) {
return (User) ois.readObject();
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
return null;
}
}
}
class User implements Serializable {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
@Override
public String toString() {
return STR."User {name='\{name}\{'\''}, age=\{age}\{'}'}";
}
}
Output:

References:
- ObjectOutputStream - Documentation for writing objects to an OutputStream.
- ObjectInputStream - Documentation for reading objects from an InputStream.
- Serializable Interface - Documentation for the Serializable interface.
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!