Write object to file java

Write object to file java

To write object to file java you will have to follow below steps:

  • Create file in directory
  • Create Class whose object you want to save in file (Note: Class should implements Serrializable interface whose object you going are going to save in file)
  • Finally write content into file

Please have java class below:

package com.javahonk.transienttest;

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

public class WriteObjectToFileJava 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;

	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);
	    SaveObjectJava saveObject = new SaveObjectJava();
	    saveObject.setName("Java Honk");
	    oos.writeObject(saveObject);
	    System.out.println("Object written successfully to file");

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

	}

    }

}

class SaveObjectJava implements Serializable {

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

    public String getName() {
	return name;
    }

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

}

 

Output:

Write object to file java

Write object to file java is done .

Leave a Reply

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