java.io.NotSerializableException

If you are getting java.io.NotSerializableException while trying to write into file shown below:

java.io.NotSerializableException: TransientVar
	at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
	at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
	at TransientTest.main(TransientTest.java:27)

 

Solution: It means your class needs to implements Serializable interface. Please see below sample class which is writing into file where it implements Serializable interface:

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 WriteToFileTest {

    public static void main(String[] args) {

	ObjectOutputStream oos = null;

	// create new file if not exits
	File file = new File("C:\\JavaHonk\\Test.txt");
	try {
	    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 written to file successfully");

	} catch (IOException e) {
	    e.printStackTrace();
	}

    }

}

class SaveSerializableObject implements Serializable {

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

    public String getName() {
	return name;
    }

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

}

 

Output:

java.io.NotSerializableException

That’s it for java.io.NotSerializableException

Leave a Reply

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