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


Please Help Members By Posting Answers For Below Questions

How do you control extraneous variables?

507


Are registers volatile?

536


Difference between current previous versions of Java?

559


What is the default execution method in java?

625


Can we write class inside a class in java?

553






Explain static nested classes ?

599


What is jvm? How its run?

664


What does pointer mean?

546


Can we sort arraylist in java?

565


If an object is garbage collected, can it become reachable again?

548


Where is core java used?

588


What does it mean to be immutable?

552


Can static method access instance variables ?

601


What are the restriction imposed on a static method or a static block of code?

598


Why parsing is done?

508