Java: Object File IO – Output (Swing)

Posted February 14, 2006 by William_Wilson in Java programming

Outputting a file with objects instead of text can be achieved by following a few simple steps. Read on to find out how this is done.


Outputting a file in Java is similar to outputting text, but there are a few key differences:
-If the Object is of your own personal class/creation, it needs to implement java.io.serializable. The implementation and reasons will be described in the “serializable” tech-recipe.
-The stream used is as follows: java.io.ObjectOutputStream.
-There is only one output command, as all items output must be objects (i.e., String, Integer, etc.) either by using wrappers (discussed under the “wrapper” tech-recipe) or as an Object by default.

*All Java supplied Objects are serializable.

Since a String is an object (array of chars as a class), I will use it here. However, if Integers (the objects, not the elementary variable int), then the objects are not recognizable in the output file, as they are serialized.

ObjectStream can only throw one main error.
IOException: thrown when there is an error writing to, or creating the specified file

CODE example:
import java.io.*;
public class ObjectStreamExample{
public static void main(String args[]){
try{
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(“myFile3.dat”));
String s = “William_Wilson. §”;
out.writeObject(s);
out.close();
}catch(IOException e){
System.out.println(“Error writting the specified file.”);
}
}}

NOTE: The object should be created before the .write() line and not created as a String inside the ( ).

*That is all there is to it. Just be careful when using your own classes because they must serializable. They cannot be read if the class which creates the object is modified.

Questions and Comments: [email protected]
-William. § (marvin_gohan)

The Conversation

Follow the reactions below and share your own thoughts.