How do I read multiple object in File using while loop? | Core Java Forum
V
Vikrant Posted on 01/08/2021

Hi Yogesh, 

 

If my file having an multiple object in it then how do I read the same in file using while loop?

How do I store the object and print it using while loop?

 


Y
Yogesh Chawla Replied on 01/08/2021

You can use this:

package com.programming.class19;

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;

public class ReadWriteObjects {

	public static void main(String[] args) throws IOException, ClassNotFoundException {
		
		String str = new String("ABCDEF");
		int i = 898989;
		boolean bl = true;
		Integer iO = new Integer(123);
		
		FileOutputStream out = new FileOutputStream("C:/ABC.txt");
		ObjectOutputStream oos = new ObjectOutputStream(out);
		oos.writeObject(str);
		oos.writeObject(i);
		oos.writeObject(bl);
		oos.writeObject(iO);
		oos.close();
		
		ObjectInputStream ois = new ObjectInputStream(new FileInputStream("C:/ABC.txt"));
		Set<Object> output = readAllObjects(ois);
		
		Iterator<Object> it = output.iterator();
		while(it.hasNext()) {
			System.out.println(it.next() + " ");
		}
		//System.out.print(ois.readObject());
		ois.close();
		
	}
	
	static Set<Object> readAllObjects(ObjectInputStream ois) throws ClassNotFoundException, IOException{
		Set<Object> result = new HashSet<>();
		try { 
		  for (;;) { 
		    result.add((Object)ois.readObject());
		  }
		} catch (EOFException e) {
		  // End of stream
		} 
		return result;
	}
}