Loop Reading To Array?


DevX Home    Today's Headlines   Articles Archive   Tip Bank   Forums   

Results 1 to 5 of 5

Thread: Loop Reading To Array?

Hybrid View

  1. #1
    Join Date
    Mar 2005
    Posts
    24

    Question Loop Reading To Array?

    Hi, I'm reading a serializable text file into an ArrayList by the following code:
    Code:
    			if (e.getSource() == readBtn){
    			ObjectInput input = null;
    			try
    			{
    			
    			
                InputStream file = new FileInputStream( "Books1.ser" );
          		InputStream buffer = new BufferedInputStream( file );
         		input = new ObjectInputStream ( buffer );
    
    			}
    		catch(Exception error)
    		{
    			System.err.println("Error inputting the file");
    		}
    		try
    		{
    		
    				
    				ArrayList recoveredQuarks = (ArrayList)input.readObject();
    				Iterator quarksItr = recoveredQuarks.iterator();
          			while ( quarksItr.hasNext() ) {
            			System.out.println( (String)quarksItr.next() );
    				}
    				input.close();
    
    			}
    		catch(Exception error)
    		{
    			System.err.println("Error reading from file");
    		}
    		}
    }
    It is printing out the first set in the text file, but doesn't print the next set.
    Any help with this please?
    THanks.

  2. #2
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560
    Im not sure what happends here but why are you using an iterator to scan an Arraylist ? And are the objects in the list Strings ?.

    for (int i=0; i<recoveredQuarks.size(); i++) {
    System.out.println((String)recoveredQuarks.get(i));
    }

    If the above doesn't help then your fiel has only one element.
    eschew obfuscation

  3. #3
    Join Date
    Mar 2005
    Posts
    24
    Your right, the arraylist is only getting one serialized object from the file.
    So I need to code it so that when I read the file into the arraylist that it ands all the serialized objects that are in the file. I think it would go something like while ( not end of file) add each object.
    Would you be abloe to tell me what the code should be like to do this please?
    THis is what it looks like atm:
    Code:
    	public void actionPerformed(ActionEvent e)
    	{
    		//Save Employee object
    		if (e.getSource() == saveBtn)
    		{
    		try
    		{
    			//Create file and object output streams
    			outputBook = new FileOutputStream("Books1.ser",true);
    			objSaveBook = new ObjectOutputStream(outputBook);
    		}
    				catch(Exception error)
    		{
    			System.err.println("Error outputting file");
    		}
    		try
    		{
    		strTitle = txtTitle.getText();
    		strDesc = txtDesc.getText();
    		strAuthor = txtAuthor.getText();
    		strGenre = txtGenre.getText();
    		
    		ArrayList arraylist = new ArrayList();
    			
    			
    			arraylist.add(strTitle);
    			arraylist.add(strAuthor);
    			arraylist.add(strDesc);
    			arraylist.add(strGenre);
    			objSaveBook.writeObject(arraylist);
    			objSaveBook.flush();
    			txtTitle.setText("");
    			txtDesc.setText("");
    			txtAuthor.setText("");
    			txtGenre.setText("");
    			txtTitle.requestFocus();
    			objSaveBook.close(); //Close the object output stream
    			outputBook.close();
    		}
    		catch(Exception error)
    		{
    			System.err.println("Error writing to file");
    		}
    		}
    			if (e.getSource() == readBtn){
    			ObjectInput input = null;
    			try
    			{
    			
    			
                InputStream file = new FileInputStream( "Books1.ser" );
          		InputStream buffer = new BufferedInputStream( file );
         		input = new ObjectInputStream ( buffer );
    
    			}
    		catch(Exception error)
    		{
    			System.err.println("Error inputting the file");
    		}
    		try
    		{
    		
    				
    				ArrayList recoveredQuarks = (ArrayList)input.readObject();
    				Iterator quarksItr = recoveredQuarks.iterator();
          			while ( quarksItr.hasNext() ) {
            			System.out.println( (String)quarksItr.next() );
    				}
    				input.close();
    
    			}
    		catch(Exception error)
    		{
    			System.err.println("Error reading from file");
    		}
    		}
    }

  4. #4
    Join Date
    Nov 2004
    Location
    Norway
    Posts
    1,560

    The job is done in the serializable classes

    I have made an example here, as simple as possible. You should be able
    to see the trick here.

    Good luck

    Code:
    /**
     *  Simple serialization example
     */
    
    import java.io.*;
    import java.util.*;
    
    
    /**
     * Class for storing car owner info
     */
    class CarOwner implements Serializable {
      private String name=null;
      private String address=null;
    
      // constructor
      public CarOwner(String name, String address) {
        this.name=name;
        this.address=address;
      }
      public String toString() {
        return "Owner: " + name + ", Address: " + address;
      }
      // write the class
      private void writeObject(ObjectOutputStream out) throws IOException {
        Serilalizing.serializeStringOut(name,out);
        Serilalizing.serializeStringOut(address,out);
      }
      // read the class, in same sequence as it was written...
      private void readObject(ObjectInputStream in)
          throws IOException, ClassNotFoundException {
        name=Serilalizing.serializeStringIn(in);
        address=Serilalizing.serializeStringIn(in);
     }
    }
    
    /**
     * Class for storing basic car information
     */
    class CarInfo implements Serializable {
      private String make = null;
      private String model = null;
      private int year = -1;
      private CarOwner owner=null;
    
      // constructor
      public CarInfo(String make, String model, int year, CarOwner owner) {
        this.make = make;
        this.model = model;
        this.year = year;
        this.owner=owner;
      }
      public String toString() {
        return "Make: " + make + ", Model: " + model + ", Year: " + year + " "+owner;
      }
      // write the class
      private void writeObject(ObjectOutputStream out) throws IOException {
        Serilalizing.serializeStringOut(make,out);
        Serilalizing.serializeStringOut(model,out);
        out.writeInt(year);
        out.writeObject(owner);
      }
      // read the class, in same sequence as it was written...
      private void readObject(ObjectInputStream in)
         throws IOException, ClassNotFoundException {
       make=Serilalizing.serializeStringIn(in);
       model=Serilalizing.serializeStringIn(in);
       year=in.readInt();
       owner=(CarOwner)in.readObject();
     }
    }
    /**
     * Car Driver class ...hehe
     */
    public class Serilalizing {
      public Serilalizing() {}
      public void makeAndStoreCars (String outPath) throws IOException {
        ArrayList list=new ArrayList();
        FileOutputStream ostream = new FileOutputStream(outPath);
        ObjectOutputStream out = new ObjectOutputStream(ostream);
        // make some owners and cars and store in ArrayList
        CarOwner owner1=new CarOwner("John Smith","Penny Lane 123");
        CarOwner owner2=new CarOwner("Donald Duck","QuackStreet 313");
        CarInfo car1=new CarInfo("Ford","Focus",2001,owner1);
        list.add(car1);
        CarInfo car2=new CarInfo("Volvo","V70",2004,owner2);
        list.add(car2);
        out.writeObject(list);
        out.close();  // <---- important
        System.out.println("Stored: "+list.size()+" cars");
      }
      public void readCarInfo (String inPath)
          throws IOException, ClassNotFoundException {
        FileInputStream istream = new FileInputStream(inPath);
        ObjectInputStream in = new ObjectInputStream(istream);
        ArrayList list=(ArrayList)in.readObject();
        System.out.println("Read: "+list.size()+" cars");
        for (int i=0;i<list.size();i++) {
          CarInfo car=(CarInfo)list.get(i);
          System.out.println(car);
        }
        in.close(); // <--- important
      }
      /**
       * This is for reading/writing a string as a series of bytes,
       * I have not found any other way to do this.  I have declared the two io
       * methods here as static so they can be used 'all over the place'.  I could
       * have declared these as non-static methods in both Car and CarOwner, but
       * I am too lazy.
       */
      public static void serializeStringOut(String s, ObjectOutputStream out)
          throws IOException {
        out.writeInt(s.length());
        out.write(s.getBytes());
      }
      public static String serializeStringIn(ObjectInputStream in)
          throws IOException {
        int len=in.readInt();
        byte [] b=new byte[len];
        in.read(b);
        return new String(b);
      }
      // ********************* MAIN ********************
      public static void main(String[] args) {
        Serilalizing se = new Serilalizing();
        try {
          se.makeAndStoreCars("c:\\tmp\\acarlist.ser");
          se.readCarInfo("c:\\tmp\\acarlist.ser");
        }
        catch (IOException ex) {
          ex.printStackTrace();
        }
        catch (ClassNotFoundException ex) {
          ex.printStackTrace();
        }
      }
    }
    Last edited by sjalle; 03-10-2005 at 02:58 AM.
    eschew obfuscation

  5. #5
    Join Date
    Mar 2005
    Posts
    24
    Hey thanks for that it seems to work now. All i have to do is make it look nice

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center
 
 
FAQ
Latest Articles
Java
.NET
XML
Database
Enterprise
Questions? Contact us.
C++
Web Development
Wireless
Latest Tips
Open Source


   Development Centers

   -- Android Development Center
   -- Cloud Development Project Center
   -- HTML5 Development Center
   -- Windows Mobile Development Center