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
What are loops in java? What are three types of loops?
Given a singly linked list, find the middle of the list in a single traversal without using temporary variable.
What is identifier in java?
Can an anonymous class be declared as implementing an interface and extending a class in java programming?
What is the major drawback of internal iteration over external iteration?
Why can't we override private static methods?
What is object class in java?
Why synchronization is important?
State the merge-sort principle and its time complexity.
What are the different tags provided in jstl?
Is string passed by reference in java?
How many bits is a 64 bit byte?
How is hashset defined in java?
Why is flag used in java?
What is garbage collection? What is the process that is responsible for doing that in java?