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
Explain the reason behind ending a program with a system.exit(0)?
What is java used for on a computer?
explain the concept of virtual method invocation in polymorphism in detail?
What is an infinite loop in java? Explain with an example.
How do you call a reference in java?
What are the differences between forwarding () method and sendredirect() methods?
Can we rethrow the same exception from catch handler?
What is meant by local variable and instance variable?
Explain the scope or life time of class variables or static variables?
How concurrent hashmap works?
Write a java program for binary search?
What are kinds of processors?
What is Java Annotations?
Can a static class implement an interface?
What is math exp in java?