ObjectOutputStream — Writing Object To a File

This example illustrates using ObjectOutputStream to write an object to a file. This is a part of serialization tutorial.
import java.io.*;
class WriteObj
    public static void main(String args[]) throws Exception
        FileOutputStream fout=new FileOutputStream("obj.dat");
        ObjectOutputStream out=new ObjectOutputStream(fout);
        String st="I am written in the file.";

fout=new FileOutputStream("obj.dat"): This statement creates a FileOutputStream object pointing to obj.dat
out=new ObjectOutputStream(fout): This statement creates an ObjectOutputStream object pointing to the given FileOutputStream object.
writeObject(st): This method in the ObjectOutputStream class writes a String object to the file obj.dat

Posted by at on

Tags: Java IO,