Read object from file java

Below java class has below steps to read object from file java :

  • First create file in local directory
  • Write object with variable in file
  • Read back object with variable from file

Please have program below:

package com.javahonk.transienttest;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ReadObjectFromFile implements Serializable {

    private static final long serialVersionUID = 1L;
    static int a = 10;
    static int b = 30;

    public static void main(String[] args) {

	ObjectOutputStream oos = null;
	FileInputStream fin = null;
	ObjectInputStream ois = null;

	try {

	    // create new file if not exits
	    File file = new File("C:\\JavaHonk\\Test.txt");
	    if (file.createNewFile()) {
		System.out.println("File created!");
	    } else {
		System.out.println("File exists");
	    }

	    // Write object to file
	    FileOutputStream fout = new FileOutputStream(file);
	    oos = new ObjectOutputStream(fout);
	    SaveObject saveObject = new SaveObject();
	    saveObject.setName("Java Honk");
	    oos.writeObject(saveObject);
	    System.out.println("Object sucessfully written");

	    // Read from file
	    fin = new FileInputStream("C:\\JavaHonk\\Test.txt");
	    ois = new ObjectInputStream(fin);
	    SaveObject saveObject2 = (SaveObject) ois.readObject();
	    System.out.println("Content retrieved: "+saveObject2.getName());

	} catch (IOException e) {
	    e.printStackTrace();
	} catch (ClassNotFoundException e) {
	    e.printStackTrace();
	} finally {
	    try {
		ois.close();
		fin.close();
		oos.close();
	    } catch (IOException e) {
		e.printStackTrace();
	    }

	}

    }

}

class SaveObject implements Serializable {

    private static final long serialVersionUID = 1L;
    String name;

    public String getName() {
	return name;
    }

    public void setName(String name) {
	this.name = name;
    }

}

 

Output:

Read object from file java

Read object from file java is done.

Leave a Reply

Your email address will not be published. Required fields are marked *