Monday, June 17, 2024
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 The implementation and reasons will be described in the “serializable” tech-recipe.
-The stream used is as follows:
-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:
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)



Please enter your comment!
Please enter your name here

Most Popular


Recent Comments

error: Content is protected !!