HomeComputer programmingJava programmingJava: Object File IO - Output (Swing)

Java: Object File IO – Output (Swing)

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[]){
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(“myFile3.dat”));
String s = “William_Wilson. §”;
}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)

0 0 votes
Article Rating
Notify of
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

Cleveland Furia on How to Clear Google Activity
Sid Wohlfarth on How to Clear Google Activity
Riley Magsayo on How to Clear Google Activity
สมัครรับเครดิตฟรี ทันที on How to improve Remote Desktop Protocol Performance
Neal Wangstad on How to Clear Google Activity
Slavcho Andov on How to install Ubuntu
Slavcho Andov on How to fix bad sectors
Sheraz Ali on How to Backup Android
Would love your thoughts, please comment.x