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

Java: Object File IO – Input (Swing)

The following tech recipe explains reading in a file with objects instead of text.


This is simlar to inputting 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.ObjectInputStream.
– There is only one output command, as all items outputted 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.

The file attempted to be read is the myFile3.dat created in Java: Object file IO – output (swing).

ObjectStream can only throw one main error.
IOException: This is thrown when there is an error reading from the specified file.

CODE example:
import java.io.*;
public class ObjectStreamExample{
public static void main(String args[]){
try{
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“myFile3.dat”));
String s = (String)in.readObject();
in.close();
System.out.println(s);
}catch(IOException e){
System.out.println(“Error reading the specified file.”);
}
}}

NOTE: The object read in MUST be typecast to the type to which you are applying it, and you must also KNOW the type of object coming in.

*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)

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- 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