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[]){
ObjectInputStream in = new ObjectInputStream(new FileInputStream(“myFile3.dat”));
String s = (String)in.readObject();
}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: william_a_wilson@hotmail.com
-William. § (marvin_gohan)



Please enter your comment!
Please enter your name here

- Advertisment -

Most Popular

Recent Comments

error: Content is protected !!