Name the class that used to read objects directly from a
stream?
Answer Posted / qim2010
ObjectInputStream is used for reading and ObjectOutPutSteam is
used for writing.
Here is a simple example:
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
/**
*
* @author javadb.com
*/
public class Main {
/**
* Example method for using the ObjectInputStream class
*/
public void readPersons(String filename) {
ObjectInputStream inputStream = null;
try {
//Construct the ObjectInputStream object
inputStream = new ObjectInputStream(new
FileInputStream(filename));
Object obj = null;
while ((obj = inputStream.readObject()) != null) {
if (obj instanceof Person) {
System.out.println(((Person)obj).toString());
}
}
} catch (EOFException ex) { //This exception will be
caught when EOF is reached
System.out.println("End of file reached.");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
//Close the ObjectInputStream
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main().readPersons("myFile.txt");
}
}
| Is This Answer Correct ? | 0 Yes | 0 No |
Post New Answer View All Answers
Can we overload the main() method?
What exactly is methodology?
What is the static keyword?
What is a singleton in genetics?
What is the difference between procedural and object-oriented programs?
What is purpose of keyword void?
What is a ternary operator in java?
Can we define private and protected modifiers for the members in interfaces?
what is the purpose of the wait(), notify(), and notifyall() methods? : Java thread
What is the use of set in java?
Explain the significance of class loaders in bootstrap?
How many tetrahedral voids are there in bcc?
Can a serialized object be transferred via network?
Explain the selection sort algorithm and state its time complexity?
What is executor memory?