Sample Programs

Sample java program to store objects in file

 package org.jusfortechies.example; 

 import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
 import java.io.ObjectInputStream;
 import java.io.ObjectOutputStream;

 import org.jusfortechies.example.vo.Address;
 
 public class SaveObjectToFile {

   public static void main(String[] args) {

      try {
         // Create instances of FileOutputStream and ObjectOutputStream.
         FileOutputStream fos = new FileOutputStream("addresses.dat");
         ObjectOutputStream oos = new ObjectOutputStream(fos);

         // Create Address instance to store it in a file
         Address address = new Address("2786 Chelsey Ct", "Pittsburgh", "PA", "15052");

         // persist the Address object in addresses.dat file.
         oos.writeObject(address);

         // Flush and close the ObjectOutputStream.
         oos.flush();
         oos.close();

         // Read back the addresses saved in addresses.dat file
         FileInputStream fis = new FileInputStream("addresses.dat");
         ObjectInputStream ois = new ObjectInputStream(fis);

         address = (Address) ois.readObject();

         System.out.println(address.toString());

         ois.close();

      } catch (IOException e) {
         System.err.println("Failed to save object to file : " + e);
      } catch (ClassNotFoundException e) {
         System.err.println("Failed to save object to file : " + e);
      }
   }

 }


Below is the code for Address object used in above example.


 package org.jusfortechies.example.vo; 

 import java.io.Serializable;
  
 public class Address implements Serializable {
	
   private static final long serialVersionUID = -1347102944411534331L;

   private String address;
   private String city;
   private String state;
   private String zipcode;

   public Address(String address, String city, String state, String zipcode) {
      this.address = address;
      this.city = city;
      this.state = state;
      this.zipcode = zipcode;
   }

   public String toString() {
      return "Address: Address = " + address + ", City = " 
            + city + ", State = " + state + ", Zipcode = " + zipcode;
   }

 }




blog comments powered by Disqus