Writing and  Reading serialized Objects

[code=java]
/*hey guys i'm new to java and i have been given an exercise to make a cd collection, write it into a file and read the data back to the program.
the program is suppose to show you a menu to select from where you can add, delete, view sort, CD's when you add a CD it must be written to a file as an Object and when you want to view CDs or search for a CD the program must read the CD objects from the file they have been written to and must return a cd nam, artist and release date. the code looks like it is writing the Cd to a file but when i try to read (view or search for a cd from the file it gives an error null). so i think i'm note reading the right way.
thank you for helping .
import java.io.Serializable;
public class cd implements Serializable {
     //creating attributes
          private String cdname = null;
          private double price = 0.0;
          private String artist =null;
          private int ratings =0;
          private String genre=null;
          private String releaseDate =null;
     // creating an Empty constructor
          public cd(){
          public cd (String cdname,double price, int ratings, String genre, String artist, String releaseDate){
          this.cdname=cdname;
          this.price=price;
          this.artist=artist;
          this.ratings=ratings;
          this.genre=genre;
          this.releaseDate=releaseDate;
          public String getGenre(){
               return genre;
          public void setGenre(String genre){
               this.genre =genre;
          public String getArtist(){
               return artist;
          public void setArtist(String artist){
               this.artist=artist;
          public String getName(){
          return cdname;
          public void setName(String cdname){
          this.cdname = cdname;
          public Double getPrice(){
          return price;
          public void setPrice(double price){
          this.price = price;
          public String getReleaseDate(){
          return releaseDate;
          public void setReleaseDate(String releaseDate){
          this.releaseDate = releaseDate;
          public int getRatings(){
          return ratings;
          public void setRatings( int ratings){
          this.ratings = ratings;
import java.util.*;
public class hipHopCollection {
ArrayList<cd> list = new ArrayList <cd> ();
EasyIn ei = new EasyIn();
     private cd invoke;
     private int b;
     public void load()
          System.out.println(" You Entered " + b + " To Add A CD ");
          invoke = new cd();
          System.out.println("Please Enter A CD Name ");     
          invoke.setName(ei.readString());
          System.out.println("Please Enter A CD Price");
          invoke.setPrice(ei.readDouble());
          System.out.println("Please Give Ratings For The CD");
          invoke.setRatings(ei.readInt());
          System.out.println("Please Enter A CD release date ");
          invoke.setReleaseDate(ei.readString());
          System.out.println("Please Enter artist Name ");
          invoke.setArtist(ei.readString());
          System.out.println("Please Enter A CD Genre ");
          invoke.setGenre(ei.readString());
          list.add(invoke); // trying to add cd information to invoke.
     }// end of load
// The following method should return the Object variable invoke that holds the cd INFO
     public Object getInvoke()
     return invoke;
     public int getB()
     return b;
     public void setB()
     b=ei.readInt();
     public void menu(){
          System.out.println("......................................................... ");
          System.out.println("Hi There Please Enter A Number For Your Choice");
          System.out.println(" Pess >>");
          System.out.println("1 >> Add A CD");
          System.out.println("2 >> View List Of CD's");
          System.out.println("3 >> Sort CD's By Price");
          System.out.println("4 >> Search CD By Name");
          System.out.println("5 >> Remove CD(s) By Name");
          System.out.println("0 >> Exit");
          System.out.println(".........................................................");
          System.out.print("Please Enter Chioce >> ");     
     }// end of menu
     public void GoodBye()
          System.out.println(" You Entered " + b + " To exit Good_bye" );
          System.exit(0);
     }//end of GoodBye
     public void PriceSort()
          System.out.println(" You Entered " + b + " To Sort CD(s) By price ");
          Collections.sort(list, new SortByPrice());
          for(cd s : list)
          System.out.println(s.getName() + ": " + s.getPrice());
     }// end of PriceSort
     public void NameSearch()
               System.out.println(" You Entered " + b + " To Search CD(s) By Name ");
               System.out.println("Please Enter The Name Of The CD You Are Searching For " );
               String search = ei.readString();
               for(int i=0; i<list.size();i++){
               if(search.equalsIgnoreCase(list.get(i).getName() )){
               System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );
}//end of NameSearch
     public void ViewList()
               System.out.println(" You Entered " + b + " To view CD(s) By Name ");
               for(int i=0; i<list.size();i++)
               System.out.println(list.get(i).getName() + " " + list.get(i).getPrice() + " " + list.get(i).getRatings() + " " + list.get(i).getGenre() );
     }// end of ViewList
     public void DeleteCd()
               System.out.println(" You Entered " + b + " To Delete CD(s) By Name ");
               System.out.println("Please Enter The Name Of The CD You Want to Delete ");
               String search = ei.readString();
               for(int i=0; i<list.size();i++)
               if(search.equalsIgnoreCase(list.get(i).getName() ))
               System.out.println(list.get(i).getName());
               list.remove(i);
     }// end of DeleteCD
     public static void main(String[] args) {
     //creating an Instance of EasyIn by object ei. Easy in is a Scanner class for reading
          EasyIn ei = new EasyIn();
          ArrayList<cd> list = new ArrayList <cd> (); // creating an array cd list
          hipHopCollection call = new hipHopCollection();
          ReadWrite rw = new ReadWrite();
               while (true){
               call.menu();
               call.setB();
               //b = ei.readInt();
               if(call.getB()==0)
                    call.GoodBye();
               if(call.getB()==1)
                    call.load();
                    rw.doWriting();// trying to write the cd object to a file
               if(call.getB()==2)
               rw.doReading();// trying to read the cd object from a file
               //call.ViewList();
               if(call.getB()==3)
               call.PriceSort();
               if(call.getB()==4)
                    call.NameSearch();
               if(call.getB()==5)
                    call.DeleteCd();
     }// end of while
}// end of main
}// end of class
// importing all the packages that we will use
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.Serializable;
public class ReadWrite {
// these are all the attributes
     private String FileName ="CdCollections.dat";     
     private OutputStream output;
     private ObjectOutputStream oos;
     private FileOutputStream fos;
     private File file;
     private FileInputStream fis;
     private ObjectInputStream ois;
     //creating an empty constructor
     public ReadWrite()
     // we could initialise all the attributes inside this empty constructor
     //creating a constructor with arguments of a file name.
     public ReadWrite(File file)
          this.file=file;
          try
               //Use a FileOutputStream to send data to a file called CdCollections.dat
               fos = new FileOutputStream(file,true);
               Use an ObjectOutputStream to send object data to the
               FileOutputStream for writing to disk.
               oos = new ObjectOutputStream (fos);
               fis=new FileInputStream(file);
               ois = new ObjectInputStream(fis);
          catch(FileNotFoundException e)
               System.out.println("File Not Found");
          catch(IOException a)
               System.out.println(a.getMessage());
               System.out.println("Please check file permissions of if file is not corrupt");
     }// end of the second constructor
     //the following lines of code will be the accessors and mutators
     * @return the output
     public OutputStream getOutput() {
          return output;
     * @param output the output to set
     public void setOutput(OutputStream output) {
          this.output = output;
     * @return the objStream
     public ObjectOutputStream getOos() {
          return oos;
     * @param objStream the objStream to set
     public void setObjStream(ObjectOutputStream objStream) {
          this.oos = oos;
     public File getFile() {
          return file;
     public void setFile(File file) {
          this.file = file;
     public FileInputStream getFis() {
          return fis;
     public void setFis(FileInputStream fis) {
          this.fis = fis;
     public ObjectInputStream getOis() {
          return ois;
     public void setOis(ObjectInputStream ois) {
          this.ois = ois;
     // the following lines of code will be the methods for reading and writing
the following method doWriting will write data from the hipHopCollections source code.
that will be all the cd information.
Pass our object to the ObjectOutputStream's
writeObject() method to cause it to be written out
to disk.
obj_out.writeObject (myObject);
     public void doWriting()
          hipHopCollection call = new hipHopCollection();
//creating an Object variable hold that will hold cd data from hipHopCollections invoke
          Object hold = call.getInvoke();// THI COULD BE THE PART WHERE I MADE A MISTAKE
          ReadWrite stream = new ReadWrite (new File(FileName));
          try
          Pass our object to the ObjectOutputStream's
          writeObject() method to cause it to be written out to disk.
          stream.getOos().writeObject(hold);
               stream.getOos().writeObject(hold);
               stream.getOos().close();
               System.out.println("Done writing Object");
          catch (IOException e)
               System.out.println(e.getMessage());
               System.out.println("Program Failed To Write To The File");     
          finally
               System.out.println("The program Has come To An End GoodBye");
     }// end of method DoWriting
The following method is for reading data from the file written by the above method named
DoWriting
// PLEASE NOT THIS IS THE METHOD THAT GIVES ME NULL EXCEPTION
     public void doReading()
     ReadWrite read = new ReadWrite(new File(FileName));
          try{
               //System.out.println("I AM NOW INSIDE THE TRY TO READ");
               Object obj = read.getOis().readObject();
               System.out.println("tried reading the object");
               cd c = (cd)obj; // trying to cast the object back to cd type
               System.out.println("I have typed cast the Object");               
               System.out.println(c.getName());
               System.out.println(c.getGenre());
               System.out.println(c.getArtist());
               System.out.println(c.getPrice());
               System.out.println(c.getRatings());
               System.out.println(c.getReleaseDate());
               read.getOis().close();
          catch(ClassNotFoundException e)
          System.out.println(e.getMessage());
          System.out.println("THE CLASS COULD NOT BE FOUND");
          catch(IOException e)
          System.out.println(e.getMessage());// null
          System.out.println("WE COULD NOT READ THE DATA INSIDE THE FILE");
     }//end of method doReading
}// end of class ReadWrite

Cross posted
http://www.java-forums.org/new-java/59965-writing-reading-serialized-java-object.html
Moderator advice: Please read the announcement(s) at the top of the forum listings and the FAQ linked from every page. They are there for a purpose.
Then edit your post and format the code correctly.
db

Similar Messages

  • Problem with writing and reading using serialization

    I am having a problem with writing and reading an object that has another object in it. The purpose of the class is to write a order that has multiple items in it. And there will be several orders. This is for an IB project, where one of the requirements is to utilize a hierarchical composite data structure. That is, it is "one that contains more than one element and at least one of the elements is a composite data structure. Examples are, an array or linked list of records, a record that has one field that is another record, or an array". The code is shown below:
    The error produced is
    java.lang.NullPointerException
         at SamsonRubberIndustries.CustomerOrderDetails.createCustOrdDetailsScreen(CustomerOrderDetails.java:150)
         at SamsonRubberIndustries.CustomerOrderDetails$1.run(CustomerOrderDetails.java:78)
         at java.awt.event.InvocationEvent.dispatch(Unknown Source)
         at java.awt.EventQueue.dispatchEvent(Unknown Source)
         at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
         at java.awt.EventDispatchThread.run(Unknown Source)
    public class CustOrdObject implements Serializable {
         public int CustID;
         public int CustOrderID;
         public Object OrderDate;
         public InnerCustOrdObject[] innerCustOrdObj;
         public float GrandTotal;
         public int MaxItems;
         public CustOrdObject() {}
         public CustOrdObject(InnerCustOrdObject[] innerCustOrdObj,
    int CustID, int CustOrderID, Object OrderDate,
    float GrandTotal, int innerarrlength, int innerarrpos, int MaxItems) {
              this.CustID = CustID;
              this.CustOrderID = CustOrderID;
              this.OrderDate = OrderDate;
              this.GrandTotal = GrandTotal;          
              this.MaxItems = MaxItems;
              this.innerCustOrdObj = new InnerCustOrdObject[MaxItems];
         public InnerCustOrdObject[] getInnerCustOrdObj() {
              return innerCustOrdObj;
         public void setInnerCustOrdObj(InnerCustOrdObject[] innerCustOrdObj) {
              this.innerCustOrdObj = innerCustOrdObj;
         public int getCustID() {
              return CustID;
         public void setCustID(int custID) {
              CustID = custID;
         public int getCustOrderID() {
              return CustOrderID;
         public void setCustOrderID(int custOrderID) {
              CustOrderID = custOrderID;
         public Object getOrderDate() {
              return OrderDate;
         public void setOrderDate(Object orderDate) {
              OrderDate = orderDate;
         public void setGrandTotal(float grandTotal) {
              GrandTotal = grandTotal;
         public float getGrandTotal() {
              return GrandTotal;
         public int getMaxItems() {
              return MaxItems;
         public void setMaxItems(int maxItems) {
              MaxItems = maxItems;
    public class InnerCustOrdObject implements Serializable{
         public int ItemNumber;
         public float UnitPrice;
         public int QuantityRequired;
         public float TotalPrice;
         public InnerCustOrdObject() {}
         public InnerCustOrdObject(int ItemNumber, float
    UnitPrice, int QuantityRequired, float TotalPrice){
              this.ItemNumber = ItemNumber;
              this.UnitPrice = UnitPrice;
              this.QuantityRequired = QuantityRequired;
              this.TotalPrice = TotalPrice;
         public int getItemNumber() {
              return ItemNumber;
         public void setItemNumber(int itemNumber) {
              ItemNumber = itemNumber;
         public int getQuantityRequired() {
              return QuantityRequired;
         public void setQuantityRequired(int quantityRequired) {
              QuantityRequired = quantityRequired;
         public float getTotalPrice() {
              return TotalPrice;
         public void setTotalPrice(float totalPrice) {
              TotalPrice = totalPrice;
         public float getUnitPrice() {
              return UnitPrice;
         public void setUnitPrice(float unitPrice) {
              UnitPrice = unitPrice;
    import java.awt.*;
    import java.awt.event.*;
    import java.io.*;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import javax.swing.*;
    import javax.swing.table.DefaultTableCellRenderer;
    import javax.swing.table.DefaultTableModel;
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems;
         private static boolean FileExists, recFileExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.dat");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                 innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord-1);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              //TotPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++CurrentRecord;
                             //readOrder();
                             //readInnerOrderRecord(CurrentRecord);
                             setInnerFieldText(currentItem);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        //getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             //readOrder();
                             setInnerFieldText(currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             writeRecordNumber(MaxRecord);
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             currentItem++;
                             setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              System.err.println("currentItem" + currentItem);
              getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07
    Message was edited by:
    Kilik07

    ok i got reading to work to a certain extent... but the prob is i cnt seem to save my innerCustOrdObj proprly...when ever i look for a record using the gotorecordbtn, the outerobject, which is the orderDetails, seems to change but the innerCustOrdObj remains the same... heres the new code..
    public class CustomerOrderDetails extends CommonFeatures{
         //TODO
         private static int MAX_ORDERS = 200;
         private static int MAX_ORDERITEMS = 100;
         private static int MaxRecord;
         private static int CurrentRecord = 1;
         private static int currentItem;
         private static int MaxItems = 1;
         private static boolean FileExists, recFileExists;
         private static boolean RecordExists;
         private static CustOrdObject[] orderDetails = new CustOrdObject[MAX_ORDERS];
         private static InnerCustOrdObject[] innerCustOrdObj = new InnerCustOrdObject[MAX_ORDERITEMS];     
         private static File OrderDetailsFile = new File("CustOrdDetails.ser");
         private static File OrdRecordNumStore = new File("OrdRecordNumStore.txt");
         private static PrintWriter writeFile;
         private static BufferedReader readFile;
         private static ObjectOutputStream objOut;
         private static ObjectInputStream objIn;
         //Set format for date
         SimpleDateFormat simpleDF = new SimpleDateFormat("dd MM yyyy");
         //--<BEGINNING>--Declaring Interface Variables------------------------------------------//
         private JPanel innertoppanel, innercenterpanel, innerbottompanel, innerrightpanel, innerleftpanel;
         private JLabel CustIDLbl, CustOrderIDLbl, OrderedDateLbl, GrandTotLbl, ItemNumberLbl,UnitPriceLbl, QuantityReqLbl, TotPriceLbl;
         private JTextField CustIDTxt, CustOrderIDTxt, OrderedDateTxt, GrandTotTxt, ItemNumberTxt, UnitPriceTxt, QuantityReqTxt, TotPriceTxt;
         private JButton addrecordbtn, savebtn, externalprevbtn, externalnextbtn, internalprevbtn, internalnextbtn, gotorecordbtn, additemreqbtn;
         //--<END>--Declaring Interface Variables------------------------------------------------//
         public static void main(String[] args) {
              final CustomerOrderDetails COD = new CustomerOrderDetails();
              java.awt.EventQueue.invokeLater(new Runnable() {
                   public void run() {
                        try {
                             UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                             COD.createCustOrdDetailsScreen();
                        } catch (Exception eb) {
                             eb.printStackTrace();
         //--<BEGINNING>--Creating CustomerOrderDetails Screen---------------------------------------//
         public JFrame createCustOrdDetailsScreen() {
              createDefaultFrame();
              mainframe.setSize(800,500);
              createContainerPanel();
              containerpanel.add(createCustOrdDetailsTitle(), BorderLayout.NORTH);
              containerpanel.add(createCustOrdDetailsMainPanel(), BorderLayout.CENTER);
              //containerpanel.add(createCustOrdDetailsLeftNavButtons(), BorderLayout.WEST);
              //containerpanel.add(createCustOrdDetailsRightNavButtons(), BorderLayout.EAST);
              containerpanel.add(createCustOrdDetailsButtons(), BorderLayout.SOUTH);
              mainframe.setContentPane(containerpanel);
              mainframe.setLocationRelativeTo(null);
              mainframe.setVisible(true);
              //--<BEGINNING>--Checks to see whether CRecordNumberStore file exists-------------------------------//
              if (OrdRecordNumStore.exists() == true) {
                   recFileExists = true;
              }else {
                   recFileExists = false;
              if (recFileExists == true) {
                   MaxRecord = readRecordNumber();
                   CurrentRecord = MaxRecord;
                   //readOrder();
                   //readInnerOrderRecord(CurrentRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              }else{
                   MaxRecord = 1;
                   writeRecordNumber(MaxRecord);
                   CustOrderIDTxt.setText(""+MaxRecord);
                   System.out.println("Current Record " +CurrentRecord);
                   System.out.println("Max Record " +MaxRecord);
              //--<END>--Checks to see whether CRecordNumberStore file exists--------------------------------------//
              if(readOrder() != null){
                   orderDetails = (CustOrdObject[]) readOrder();
                   //CurrentRecord--;
                   //System.out.println("Current Rec Here"+CurrentRecord);
                   if(orderDetails[CurrentRecord] == null){
                        System.err.println("CustomerOrderObj 1 is null !!");
                   }else{
                        System.err.println("CustomerOrderObj 1 is  not null !!");
                   if(orderDetails[CurrentRecord].getInnerCustOrdObj() == null){
                        System.err.println("InnerCustomerOrderObj is null !!");
                   }else{
                        System.err.println("InnerCustomerOrderObj is  not null !!");
                   innerCustOrdObj = orderDetails[CurrentRecord].getInnerCustOrdObj();
                   MaxItems = orderDetails[CurrentRecord].getMaxItems();
                   if(CurrentRecord > 1 && CurrentRecord < MaxRecord){
                        externalnextbtn.setEnabled(true);
                        externalprevbtn.setEnabled(true);
                   if(CurrentRecord >= MaxRecord){
                        externalnextbtn.setEnabled(false);
                   getFieldText(CurrentRecord);
                   getInnerFieldText(MaxItems);
              }else{
                   orderDetails[CurrentRecord] = new CustOrdObject();
                   currentItem = 1;
              return mainframe;
         //--<END>--Creating CustomerOrderDetails Screen---------------------------------------------//
         public JPanel createCustOrdDetailsTitle(){
              createTitlePanel();
              titlepanel.setBackground(TxtfontColor);
              label.setText("- Customer Order Details -");
              labelpanel.setBackground(TxtfontColor);
              label.setForeground(Color.white);
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor) ;
              buttonpanel.add(createReturnToMainMenuButton());
              titlepanel.add(labelpanel, BorderLayout.WEST);
              titlepanel.add(buttonpanel, BorderLayout.EAST);
              return titlepanel;
         public JPanel createCustOrdDetailsMainPanel(){
              createmainpanel();
              mainpanel.setBackground(TxtfontColor);
              mainpanel.setLayout(new BorderLayout());          
              mainpanel.setBorder(BorderFactory.createTitledBorder(""));
              mainpanel.add(createInnerTopPanel(), BorderLayout.NORTH);
              mainpanel.add(createInnerCenterPanel(), BorderLayout.CENTER);
              mainpanel.add(createInnerBottomPanel(), BorderLayout.SOUTH);
              mainpanel.add(createInnerRightPanel(), BorderLayout.EAST);
              mainpanel.add(createInnerLeftPanel(), BorderLayout.WEST);
              return mainpanel;
         public JPanel createInnerTopPanel(){
              innertoppanel = new JPanel(new GridBagLayout());
              innertoppanel.setBackground(TxtfontColor);
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              CustIDLbl = new JLabel("Customer ID");
              CustIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustIDLbl.setFont(font);
              CustIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innertoppanel.add(CustIDLbl, GBC);     
              CustIDTxt = new JTextField(20);
              CustIDTxt.setEditable(true);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innertoppanel.add(CustIDTxt, GBC);
              GBC.gridx = 3;
              GBC.gridy = 1;
              innertoppanel.add(Box.createHorizontalStrut(220), GBC);
              OrderedDateLbl = new JLabel("Order Date");
              OrderedDateLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              OrderedDateLbl.setFont(font);
              OrderedDateLbl.setForeground(LblfontColor);
              GBC.gridx = 4;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateLbl, GBC);     
              //Get today's date
              Date todaydate = new Date();
              OrderedDateTxt = new JTextField(simpleDF.format(todaydate), 20);
              OrderedDateTxt.setHorizontalAlignment(JTextField.CENTER);
              OrderedDateTxt.setEditable(false);
              GBC.gridx = 5;
              GBC.gridy = 1;
              innertoppanel.add(OrderedDateTxt, GBC);
              CustOrderIDLbl = new JLabel("Customer Order ID");
              CustOrderIDLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              CustOrderIDLbl.setFont(font);
              CustOrderIDLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDLbl, GBC);
              CustOrderIDTxt = new JTextField(20);
              //CustOrderIDTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innertoppanel.add(CustOrderIDTxt, GBC);
              return innertoppanel;
         public JPanel createInnerCenterPanel(){
              innercenterpanel = new JPanel(new GridBagLayout());
              innercenterpanel.setBackground(TxtfontColor);
              innercenterpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              ItemNumberLbl = new JLabel("Item Number");
              ItemNumberLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              ItemNumberLbl.setFont(font);
              ItemNumberLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberLbl, GBC);     
              ItemNumberTxt = new JTextField(20);
              GBC.gridx = 2;
              GBC.gridy = 1;
              innercenterpanel.add(ItemNumberTxt, GBC);
              UnitPriceLbl = new JLabel("Unit Price");
              UnitPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              UnitPriceLbl.setFont(font);
              UnitPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceLbl, GBC);     
              UnitPriceTxt = new JTextField(20);
              //UnitPriceTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 2;
              innercenterpanel.add(UnitPriceTxt, GBC);
              QuantityReqLbl = new JLabel("Quantity Required");
              QuantityReqLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              QuantityReqLbl.setFont(font);
              QuantityReqLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqLbl, GBC);     
              QuantityReqTxt = new JTextField(20);
              //QuantityReqTxt.setEditable(false);
              GBC.gridx = 2;
              GBC.gridy = 3;
              innercenterpanel.add(QuantityReqTxt, GBC);
              TotPriceLbl = new JLabel("Total Price");
              TotPriceLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              TotPriceLbl.setFont(font);
              TotPriceLbl.setForeground(LblfontColor);
              GBC.gridx = 1;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceLbl, GBC);     
              TotPriceTxt = new JTextField(20);
              TotPriceTxt.setEditable(false);
              TotPriceTxt.addFocusListener(new FocusAdapter(){
                   public void focusGained(FocusEvent evt){
                        TotPriceTxt.setText(""+Integer.parseInt(UnitPriceTxt.getText())*Integer.parseInt(QuantityReqTxt.getText()));
              GBC.gridx = 2;
              GBC.gridy = 4;
              innercenterpanel.add(TotPriceTxt, GBC);
              return innercenterpanel;
         public JPanel createInnerBottomPanel(){
              innerbottompanel = new JPanel(new FlowLayout(FlowLayout.RIGHT));
              innerbottompanel.setBackground(TxtfontColor);
              //Setting Font Type and Size
              Font font = new Font("Arial", Font.BOLD, 11);
              GrandTotLbl = new JLabel("Grand Total");
              GrandTotLbl.setBorder(BorderFactory.createEmptyBorder(10,10,10,10));
              GrandTotLbl.setFont(font);
              GrandTotLbl.setForeground(LblfontColor);
              innerbottompanel.add(GrandTotLbl);
              innerbottompanel.add(Box.createHorizontalStrut(30));
              GrandTotTxt = new JTextField(20);
              innerbottompanel.add(GrandTotTxt);
              return innerbottompanel;
         public JPanel createInnerRightPanel(){
              innerrightpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerrightpanel.setBackground(TxtfontColor);
              innerrightpanel.setLayout(new BoxLayout(navrightpanel, BoxLayout.Y_AXIS));
              innerrightpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerrightpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalnextbtn = new JButton(createNextButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalprevbtn.setEnabled(true);
                        if(currentItem < MaxItems){
                             ++currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
                        if(currentItem == MaxItems){
                             internalnextbtn.setEnabled(false);
              innerrightpanel.add(internalnextbtn, GBC);
              return innerrightpanel;
         public JPanel createInnerLeftPanel(){
              innerleftpanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
              innerleftpanel.setBackground(TxtfontColor);
              innerleftpanel.setBorder(BorderFactory.createLoweredBevelBorder());
              innerleftpanel.setForeground(Color.BLACK);
              innerleftpanel.setLayout(new GridBagLayout());          
              GridBagConstraints GBC = new GridBagConstraints();
              GBC.fill = GridBagConstraints.HORIZONTAL;
              internalprevbtn = new JButton(createPreviousButtonIcon());
              GBC.gridx = 1;
              GBC.gridy = 1;
              internalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getInnerFieldText(currentItem);
                        internalnextbtn.setEnabled(true);
                        if(currentItem == 1){
                             internalprevbtn.setEnabled(false);
                        if(currentItem > 0){
                             --currentItem;
                             orderDetails[CurrentRecord].getInnerCustOrdObj();
                             setInnerFieldText(currentItem);
                             System.out.println("Current Item" + currentItem);
              innerleftpanel.add(internalprevbtn, GBC);
              return innerleftpanel;
         public JPanel createCustOrdDetailsButtons(){
              createbuttonpanel();
              buttonpanel.setBackground(TxtfontColor);
              externalprevbtn = new JButton(createPreviousButtonIcon());
              externalprevbtn.addActionListener(new ActionListener(){
                   public void  actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalnextbtn.setEnabled(true);
                        if(CurrentRecord == 1){
                             externalprevbtn.setEnabled(false);
                        if(CurrentRecord > 0){
                             --CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println("Current Record " + CurrentRecord);//Checking RECORD_NUM
              buttonpanel.add(externalprevbtn);
              addrecordbtn = new JButton("Add Record", createAddButtonIcon());
              addrecordbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             MaxRecord = readRecordNumber();
                             MaxRecord++;
                             CurrentRecord = MaxRecord;
                             orderDetails[CurrentRecord] = new CustOrdObject();
                             writeRecordNumber(MaxRecord);
                             MaxItems = 1;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             CustIDTxt.setText("");
                             CustOrderIDTxt.setText(""+MaxRecord);
                             //Get today's date
                             Date todaydate = new Date();
                             OrderedDateTxt.setText(""+simpleDF.format(todaydate));
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             GrandTotTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             externalnextbtn.setEnabled(false);
                             externalprevbtn.setEnabled(true);
                             System.out.println(MaxRecord);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(addrecordbtn);
              savebtn = new JButton("Save Data", createSaveButtonIcon());
              savebtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        setFieldText(CurrentRecord);
                        setInnerFieldText(MaxItems);
                        writeOrder();
                        writeRecordNumber(MaxRecord);
                        System.out.println(CurrentRecord);
                        System.out.println(MaxRecord);
              buttonpanel.add(savebtn);
              java.net.URL imageURL_AddRowIcon = CommonFeatures.class.getResource("Icons/edit_add.png");
              ImageIcon AddRowIcon = new ImageIcon(imageURL_AddRowIcon);
              additemreqbtn = new JButton("Add Item", AddRowIcon);
              additemreqbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        try{
                             //--<BEGINNING>--Clear Fields-------------------------------------------------------//
                             ItemNumberTxt.setText("");
                             UnitPriceTxt.setText("");
                             QuantityReqTxt.setText("");
                             TotPriceTxt.setText("");
                             //--<END>--Clear Fields-------------------------------------------------------------//
                             //CurrentRecord = MaxRecord;
                             MaxItems++;
                             innerCustOrdObj[MaxItems] = new InnerCustOrdObject();
                             System.out.println("Max Items "+MaxItems);
                             currentItem = MaxItems;
                             orderDetails[CurrentRecord].setMaxItems(MaxItems);
                             ///setInnerFieldText(currentItem);
                             internalnextbtn.setEnabled(false);
                             internalprevbtn.setEnabled(true);
                        } catch(Exception ec){ec.printStackTrace();}
              buttonpanel.add(additemreqbtn);
              externalnextbtn = new JButton(createNextButtonIcon());
              externalnextbtn.addActionListener(new ActionListener(){
                   public void actionPerformed(ActionEvent evt){
                        getFieldText(CurrentRecord);
                        externalprevbtn.setEnabled(true);
                        if(CurrentRecord < MaxRecord){
                             ++CurrentRecord;
                             setFieldText(CurrentRecord);
                             System.out.println(CurrentRecord);//Checking RECORD_NUM
                        if(CurrentRecord == MaxRecord){
                             externalnextbtn.setEnabled(false);
              buttonpanel.add(externalnextbtn);
              gotorecordbtn = new JButton("Go To Record", createGotoButtonIcon());
              gotorecordbtn.addActionListener(new ActionListener() {
                   public void actionPerformed(ActionEvent evt){
                         * The text from the GotorecordTxt textfield will be taken and assigned
                         * to a temporary integer variable called Find. 
                        int Find = Integer.parseInt(CustOrderIDTxt.getText());
                        for(int j=1; j <= MaxRecord; j++){
                              * Using a for loop, each record can be read using the readCustRecord
                              * method.
                             getFieldText(j);
                              * An if condition is utilized to check whether the temporary stored variable, Find,
                              * matches a field in a record. If this record is found, then using the RecordExists
                              * which was declared at the top, either a true or false statement can be assigned
                              * If the record exists, then a true statement will be assigned, if not a false
                              * statement will be assigned.
                             if(orderDetails[j].getCustOrderID() == Find){
                                  RecordExists = true;
                                  break;
                             }else{
                                  RecordExists = false;
                        if(RecordExists == false){
                              * If the RecordExists is assigned a false statement, then a message will be
                              * displayed to show that the record does not exist.
                             JOptionPane.showMessageDialog(null, "Record Does Not Exist!", "Error Message", JOptionPane.ERROR_MESSAGE, createErrorIcon());
                        }else{
                             getFieldText(Find);
              buttonpanel.add(gotorecordbtn);
              return buttonpanel;
         //TODO
         public void setFieldText(int orderID){//TODO
              orderDetails[orderID].setCustID(Integer.parseInt(CustIDTxt.getText()));
              orderDetails[orderID].setCustOrderID(Integer.parseInt(CustOrderIDTxt.getText()));
              orderDetails[orderID].setOrderDate(OrderedDateTxt.getText());
              orderDetails[orderID].setInnerCustOrdObj(innerCustOrdObj);
              orderDetails[orderID].setMaxItems(MaxItems);
              setInnerFieldText(currentItem);
              orderDetails[orderID].setGrandTotal(Float.parseFloat(GrandTotTxt.getText()));
         public void setInnerFieldText(int currentItem){//TODO
              innerCustOrdObj[currentItem] = new InnerCustOrdObject();
              innerCustOrdObj[currentItem].setMaxItems(MaxItems);
              innerCustOrdObj[currentItem].setItemNumber(Integer.parseInt(ItemNumberTxt.getText()));
              innerCustOrdObj[currentItem].setUnitPrice(Float.parseFloat(UnitPriceTxt.getText()));
              innerCustOrdObj[currentItem].setQuantityRequired(Integer.parseInt(QuantityReqTxt.getText()));
              innerCustOrdObj[currentItem].setTotalPrice(Float.parseFloat(TotPriceTxt.getText()));
         public void getFieldText(int orderID){
              CustIDTxt.setText(Integer.toString(orderDetails[orderID].getCustID()));
              CustOrderIDTxt.setText(Integer.toString(orderDetails[orderID].getCustOrderID()));
              OrderedDateTxt.setText(""+orderDetails[orderID].getOrderDate());          
              currentItem = orderDetails[orderID].getMaxItems();
              orderDetails[orderID].getInnerCustOrdObj();
              System.err.println("currentItem" + currentItem);
              //getInnerFieldText(currentItem);
              GrandTotTxt.setText(Float.toString(orderDetails[orderID].getGrandTotal()));
         public void getInnerFieldText(int currentItem){
              ItemNumberTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getItemNumber()));
              UnitPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getUnitPrice()));
              QuantityReqTxt.setText(Integer.toString(innerCustOrdObj[currentItem].getQuantityRequired()));
              TotPriceTxt.setText(Float.toString(innerCustOrdObj[currentItem].getTotalPrice()));
         public void writeOrder(){//TODO
              try {
                   objOut = new ObjectOutputStream(new FileOutputStream(OrderDetailsFile));
                   objOut.writeObject(orderDetails);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              } catch (IOException e) {
                   e.printStackTrace();
         public Object readOrder(){
              Object temporaryObj;
              try{
                   objIn = new ObjectInputStream(new FileInputStream(OrderDetailsFile));
                   temporaryObj = objIn.readObject();               
                   CustOrdObject[] blah = (CustOrdObject[]) temporaryObj;
                   /*               System.out.println("Outer: "+blah[1].getCustID());
                   InnerCustOrdObject[] whee = blah[1].getInnerCustOrdObj();
                   System.out.println("Inner: "+whee[1].getItemNumber());*/
                   objIn.close();
                   System.out.println("Read Worky!");
                   return temporaryObj;
              }catch(Exception e){
                   e.printStackTrace();
                   System.out.println("Read No Worky!");
                   return null;
         public void writeRecordNumber(int MaxRecord){
              try{
                   objOut = new ObjectOutputStream(new FileOutputStream(OrdRecordNumStore));
                   objOut.writeObject(MaxRecord);
                   System.out.println("WORKING!");
                   objOut.flush();
                   objOut.close();
              }catch(Exception e){e.printStackTrace();}
         public int readRecordNumber() {
              try {
                   objIn = new ObjectInputStream(new FileInputStream(OrdRecordNumStore));
                   int temporaryObj = Integer.parseInt(objIn.readObject().toString());
                   objIn.close();
                   System.out.println("Read Number Worky!");
                   return temporaryObj;
              } catch (Exception e) {
                   e.printStackTrace();
                   System.out.println("Read Number No Worky!");
                   return -1;
    }Message was edited by:
    Kilik07

  • Saving and loading serialized objects (StreamCorruptedException)

    Hello,
    I am relatively new to Serialization (coming to that, a bit new to Java too) and I am having a problem with the following:
    I am saving a number of serialized objects (all of the same class) in a file using the following way (the method is called multiple times to save a list of TeamMember objects):
    Note: TeamMember is a custom class.
    public void addTeamMember(TeamMember p) {
                outputStream = new ObjectOutputStream( new FileOutputStream( "team.dat", true ) );
                outputStream.writeObject( p );
                outputStream.flush();
                outputStream.close();
                outputStream = null;
    }Then I'm trying to retrieve the objects from the file and display them. The method used is the following (it will loop through the file until found or it throws an EOFException. Is using the EOFException good practice to search through the entire file?):
    public TeamMember getTeamMember(String id) {
            TeamMember currentMember = null;
            try {
                boolean found = false;           
                inputStream = new ObjectInputStream( new FileInputStream( "team.dat" ) );
                while ( !found ) {
                    currentMember = (TeamMember)inputStream.readObject();
                    if ( currentMember.getId().equals( id ) )
                        found = true;
                } // end while
                closeInputFile();
                return currentMember;
            } // end try
            catch ( EOFException e ) { // end of file reached
                closeInputFile();           
                return null;
            } // end catch
            catch ( IOException e ) {
                closeInputFile();
                System.err.println( e.getMessage() );
                return null;
            } // end catch
        }Now as a test, I am adding 3 members with IDs 1, 2 and 3 respectively. Then I am calling getTeamMember three times with the different IDs. With ID "1", it works fine. When I give it ID 2, it gives an IOException with message "StreamCorruptedException: invalid type code: AC".
    While tracing the program, I've seen that it always gives me that error when reading past the first object saved in the file.
    Am I saving the objects in a wrong way, or reading them is done incorrectly?
    Any help is much appreciated.
    I hope I was clear enough, and that I posted in the correct forum.
    Thanks in advance.
    Andrew.

    If that is so, might you hint me for a work around?
    I want to append objects in a single file, then be able to find and read an object from the file.
    Thanks again.
    Andrew

  • Problem with ArrayLists and writing and reading from a .dat file (I think)

    I'm brand new to this forum, but I'm sure hoping someone can help me with a problem I'm having with ArrayLists. This program was originally created with an array of objects that were displayed on a GUI with jtextFields, then cycling thru them via jButtons: First, Next, Previous, Last. Now I need to add the ability to modify, delete and add records. Both iterations of this program needed to write to and read from a .dat file.
    It worked just like it was suppose to when I used just the array, but now I need to use a "dynamic array" that will grow or shrink as needed: i.e. an ArrayList.
    When I aded the ArrayList I had the ArrayList use toArray() to fill my original array so I could continue to use all the methods I'd created for using with my array. Now I'm getting a nullPointerException every time I try to run my program, which means somewhere I'm NOT filling my array ???? But, I'm writing just fine to my .dat file, which is confusing me to no end!
    It's a long program, and I apologize for the length, but here it is. There are also 2 class files, a parent and 1 child below Inventory6. This was written in NetBeans IDE 5.5.1.
    Thank you in advance for any help anyone can give me!
    LabyBC
    package my.Inventory6;
    import java.awt.Container;
    import java.awt.Dimension;
    import java.awt.GridBagConstraints;
    import java.awt.GridBagLayout;
    import java.awt.Insets;
    import java.awt.Toolkit;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.text.DecimalFormat;
    import javax.swing.JOptionPane;
    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JLabel;
    import javax.swing.JTextField;
    import java.io.*;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.lang.IllegalStateException;
    import java.util.NoSuchElementException;
    import java.util.ArrayList;
    import java.text.NumberFormat;
    // Class Inventory6
    public class Inventory6 extends javax.swing.JFrame {
    private static InventoryPlusColor[] inventory;
    private static ArrayList inList;
    // create a tool that insure the specified format for a double number, when displayed
    private DecimalFormat doubleFormat = new DecimalFormat( "0.00" );
    private DecimalFormat singleFormat = new DecimalFormat( "0");
    // the index within the array of products of the current displayed product
    private int currentProductIndex;
    /** Creates new form Inventory6 */
    public Inventory6() {
    initComponents();
    currentProductIndex = 0;
    } // end Inventory6()
    private static InventoryPlusColor[] getInventory() {
    ArrayList<InventoryPlusColor> inList = new ArrayList<InventoryPlusColor>();
    inList.add(new InventoryPlusColor(1, "Couch", 3, 1250.00, "Blue"));
    inList.add(new InventoryPlusColor(2, "Recliner", 10, 525.00, "Green"));
    inList.add(new InventoryPlusColor(3, "Chair", 6, 125.00, "Mahogany"));
    inList.add(new InventoryPlusColor(4, "Pedestal Table", 2, 4598.00, "Oak"));
    inList.add(new InventoryPlusColor(5, "Sleeper Sofa", 4, 850.00, "Yellow"));
    inList.add(new InventoryPlusColor(6, "Rocking Chair", 2, 459.00, "Tweed"));
    inList.add(new InventoryPlusColor(7, "Couch", 4, 990.00, "Red"));
    inList.add(new InventoryPlusColor(8, "Chair", 12, 54.00, "Pine"));
    inList.add(new InventoryPlusColor(9, "Ottoman", 3, 110.00, "Black"));
    inList.add(new InventoryPlusColor(10, "Chest of Drawers", 5, 598.00, "White"));
    for (int j = 0; j < inList.size(); j++)
    System.out.println(inList);
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    return inventory;
    } // end getInventory() method
    /** This method is called from within the constructor to
    * initialize the form.
    * WARNING: Do NOT modify this code. The content of this method is
    * always regenerated by the Form Editor.
    // <editor-fold defaultstate="collapsed" desc=" Generated Code ">
    private void initComponents() {
    jPanel1 = new javax.swing.JPanel();
    IDNumberLbl = new javax.swing.JLabel();
    IDNumberField = new javax.swing.JTextField();
    prodNameLbl = new javax.swing.JLabel();
    prodNameField = new javax.swing.JTextField();
    colorLbl = new javax.swing.JLabel();
    colorField = new javax.swing.JTextField();
    unitsInStockLbl = new javax.swing.JLabel();
    unitsInStockField = new javax.swing.JTextField();
    unitPriceLbl = new javax.swing.JLabel();
    unitPriceField = new javax.swing.JTextField();
    invenValueLbl = new javax.swing.JLabel();
    invenValueField = new javax.swing.JTextField();
    restockingFeeLbl = new javax.swing.JLabel();
    restockingFeeField = new javax.swing.JTextField();
    jbtFirst = new javax.swing.JButton();
    jbtNext = new javax.swing.JButton();
    jbtPrevious = new javax.swing.JButton();
    jbtLast = new javax.swing.JButton();
    jbtAdd = new javax.swing.JButton();
    jbtDelete = new javax.swing.JButton();
    jbtModify = new javax.swing.JButton();
    jbtSave = new javax.swing.JButton();
    jPanel2 = new javax.swing.JPanel();
    searchIDNumLbl = new javax.swing.JLabel();
    searchIDNumbField = new javax.swing.JTextField();
    jbtSearch = new javax.swing.JButton();
    searchResults = new javax.swing.JLabel();
    jbtExit = new javax.swing.JButton();
    jbtExitwoSave = new javax.swing.JButton();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Inventory Program"));
    IDNumberLbl.setText("ID Number");
    IDNumberField.setEditable(false);
    prodNameLbl.setText("Product Name");
    prodNameField.setEditable(false);
    colorLbl.setText("Product Color");
    colorField.setEditable(false);
    colorField.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    colorFieldActionPerformed(evt);
    unitsInStockLbl.setText("Units In Stock");
    unitsInStockField.setEditable(false);
    unitPriceLbl.setText("Unit Price $");
    unitPriceField.setEditable(false);
    invenValueLbl.setText("Inventory Value $");
    invenValueField.setEditable(false);
    restockingFeeLbl.setText("5% Restocking Fee $");
    restockingFeeField.setEditable(false);
    javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
    jPanel1.setLayout(jPanel1Layout);
    jPanel1Layout.setHorizontalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(unitPriceLbl)
    .addComponent(unitsInStockLbl)
    .addComponent(colorLbl)
    .addComponent(prodNameLbl)
    .addComponent(IDNumberLbl)
    .addComponent(restockingFeeLbl)
    .addComponent(invenValueLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(IDNumberField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(prodNameField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(colorField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE)
    .addComponent(invenValueField, javax.swing.GroupLayout.DEFAULT_SIZE, 176, Short.MAX_VALUE))
    .addContainerGap())
    jPanel1Layout.setVerticalGroup(
    jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel1Layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(IDNumberLbl)
    .addComponent(IDNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(prodNameLbl)
    .addComponent(prodNameField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(colorField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(colorLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitsInStockField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitsInStockLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(unitPriceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(unitPriceLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(restockingFeeField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(restockingFeeLbl))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 10, Short.MAX_VALUE)
    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(invenValueField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(invenValueLbl))
    .addContainerGap())
    jbtFirst.setText("First");
    jbtFirst.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtFirstActionPerformed(evt);
    jbtNext.setText("Next");
    jbtNext.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtNextActionPerformed(evt);
    jbtPrevious.setText("Previous");
    jbtPrevious.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtPreviousActionPerformed(evt);
    jbtLast.setText("Last");
    jbtLast.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtLastActionPerformed(evt);
    jbtAdd.setText("Add");
    jbtAdd.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtAddActionPerformed(evt);
    jbtDelete.setText("Delete");
    jbtModify.setText("Modify");
    jbtModify.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtModifyActionPerformed(evt);
    jbtSave.setText("Save");
    jbtSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtSaveActionPerformed(evt);
    jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEtchedBorder(), "Search by:"));
    searchIDNumLbl.setText("Item Number:");
    jbtSearch.setText("Search");
    searchResults.setFont(new java.awt.Font("Tahoma", 1, 12));
    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(searchIDNumLbl)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(259, 259, 259)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 213, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtSearch, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, 143, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jPanel2Layout.setVerticalGroup(
    jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(searchIDNumLbl)
    .addComponent(searchIDNumbField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addGap(32, 32, 32)
    .addComponent(searchResults, javax.swing.GroupLayout.PREFERRED_SIZE, 17, javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(jPanel2Layout.createSequentialGroup()
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtSearch)))
    .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
    jbtExit.setText("Save and Exit");
    jbtExit.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitActionPerformed(evt);
    jbtExitwoSave.setText("Exit");
    jbtExitwoSave.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jbtExitwoSaveActionPerformed(evt);
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 248, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 44, Short.MAX_VALUE)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
    .addComponent(jbtExitwoSave, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addComponent(jbtExit)))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtFirst)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtNext)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtPrevious)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtLast))
    .addGroup(layout.createSequentialGroup()
    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
    .addGap(12, 12, 12)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jbtAdd)
    .addComponent(jbtDelete)
    .addComponent(jbtModify)
    .addComponent(jbtSave))))
    .addContainerGap())
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtFirst, jbtLast, jbtNext, jbtPrevious});
    layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {jbtAdd, jbtDelete, jbtModify, jbtSave});
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(21, 21, 21)
    .addComponent(jbtAdd)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtDelete)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtModify)
    .addGap(39, 39, 39)
    .addComponent(jbtSave))
    .addGroup(layout.createSequentialGroup()
    .addContainerGap()
    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jbtFirst)
    .addComponent(jbtNext)
    .addComponent(jbtPrevious)
    .addComponent(jbtLast))
    .addGap(15, 15, 15)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGroup(layout.createSequentialGroup()
    .addComponent(jbtExit)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jbtExitwoSave)))
    .addContainerGap())
    pack();
    }// </editor-fold>
    private void jbtExitwoSaveActionPerformed(java.awt.event.ActionEvent evt) {                                             
    System.exit(0);
    private void jbtSaveActionPerformed(java.awt.event.ActionEvent evt) {                                       
    String prodNameMod, colorMod;
    double unitsInStockMod, unitPriceMod;
    int idNumMod;
    idNumMod = Integer.parseInt(IDNumberField.getText());
    prodNameMod = prodNameField.getText();
    unitsInStockMod = Double.parseDouble(unitsInStockField.getText());
    unitPriceMod = Double.parseDouble(unitPriceField.getText());
    colorMod = colorField.getText();
    if(currentProductIndex == inventory.length) {
    inList.add(new InventoryPlusColor(idNumMod, prodNameMod,
    unitsInStockMod, unitPriceMod, colorMod));
    InventoryPlusColor[] inventory = (InventoryPlusColor[]) inList.toArray
    (new InventoryPlusColor[inList.size()]);
    } else {
    inventory[currentProductIndex].setIDNumber(idNumMod);
    inventory[currentProductIndex].setProdName(prodNameMod);
    inventory[currentProductIndex].setUnitsInStock(unitsInStockMod);
    inventory[currentProductIndex].setUnitPrice(unitPriceMod);
    inventory[currentProductIndex].setColor(colorMod);
    displayProduct(inventory[currentProductIndex]);
    private static void writeInventory(InventoryPlusColor i,
    DataOutputStream out) {
    try {
    out.writeInt(i.getIDNumber());
    out.writeUTF(i.getProdName());
    out.writeDouble(i.getUnitsInStock());
    out.writeDouble(i.getUnitPrice());
    out.writeUTF(i.getColor());
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception writing data",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } //end writeInventory()
    private static DataOutputStream openOutputStream(String name) {
    DataOutputStream out = null;
    try {
    File file = new File(name);
    out =
    new DataOutputStream(
    new BufferedOutputStream(
    new FileOutputStream(file)));
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error", "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return out;
    } // end openOutputStream()
    private static void closeFile(DataOutputStream out) {
    try {
    out.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeFile()
    private static DataInputStream getStream(String name) {
    DataInputStream in = null;
    try {
    File file = new File(name);
    in = new DataInputStream(
    new BufferedInputStream(
    new FileInputStream(file)));
    } catch (FileNotFoundException e) {
    JOptionPane.showMessageDialog(null, "The file doesn't exist",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Error creating file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    return in;
    private static void closeInputFile(DataInputStream in) {
    try {
    in.close();
    } catch (IOException e) {
    JOptionPane.showMessageDialog(null, "I/O Exception closing file",
    "", JOptionPane.ERROR_MESSAGE);
    System.exit(0);
    } // end closeInputFile()
    private double entireInventory() {
    // a temporary double variable that the method will return ...
    // after each product's inventory is added to it
    double entireInventory = 0;
    // loop to control number of products
    for (int index = 0; index < inventory.length; index++) {
    // add each inventory to the entire inventory
    entireInventory += inventory[index].setInventoryValue();
    } // end loop to control number of products
    return entireInventory;
    } // end method entireInventory
    private void jbtLastActionPerformed(java.awt.event.ActionEvent evt) {                                       
    currentProductIndex = inventory.length-1; // move to the last product
    // display the information for the last product
    displayProduct(inventory[currentProductIndex]);
    private void jbtPreviousActionPerformed(java.awt.event.ActionEvent evt) {                                           
    if (currentProductIndex != 0) // it's not the first product displayed
    currentProductIndex -- ; // move to the previous product (decrement the current index)
    } else // the first product is displayed
    currentProductIndex = inventory.length-1; // move to the last product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtNextActionPerformed(java.awt.event.ActionEvent evt) {                                       
    if (currentProductIndex != inventory.length-1) // it's not the last product displayed
    currentProductIndex ++ ; // move to the next product (increment the current index)
    } else // the last product is displayed
    currentProductIndex = 0; // move to the first product
    // after the current product index is set, display the information for that product
    displayProduct(inventory[currentProductIndex]);
    private void jbtFirstActionPerformed(java.awt.event.ActionEvent evt) {                                        
    currentProductIndex = 0;
    // display the information for the first product
    displayProduct(inventory[currentProductIndex]);
    private void colorFieldActionPerformed(java.awt.event.ActionEvent evt) {                                          
    // TODO add your handling code here:
    private void jbtModifyActionPerformed(java.awt.event.ActionEvent evt) {                                         
    prodNameField.setEditable(true);
    prodNameField.setFocusable(true);
    unitsInStockField.setEditable(true);
    unitPriceField.setEditable(true);
    private void jbtAddActionPerformed(java.awt.event.ActionEvent evt) {                                      
    IDNumberField.setText("");
    IDNumberField.setEditable(true);
    prodNameField.setText("");
    prodNameField.setEditable(true);
    colorField.setText("");
    colorField.setEditable(true);
    unitsInStockField.setText("");
    unitsInStockField.setEditable(true);
    unitPriceField.setText("");
    unitPriceField.setEditable(true);
    restockingFeeField.setText("");
    invenValueField.setText("");
    currentProductIndex = inventory.length;
    private void jbtExitActionPerformed(java.awt.event.ActionEvent evt) {                                       
    DataOutputStream out = openOutputStream("inventory.dat");
    for (InventoryPlusColor i : inventory)
    writeInventory(i, out);
    closeFile(out);
    System.exit(0);
    private static InventoryPlusColor readProduct(DataInputStream in) {
    int idNum = 0;
    String prodName = "";
    double inStock = 0.0;
    double pric

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • Writing and reading txt file, GUI components

    <b>HI GUYS I AM JUST NEW TO JAVA AND I AM TRYING TO LEARN SOME MORE IN JAVA. SO I NEED HELP FROM YOU GREAT GUYS WHO KNOWS MORE & MORE THING THAN ME. I CODE A GUI FOR THIS PROGRAM. THE CODE IS BELOW. <b/>
    This program has to read a txt file to create Food objects which will consist of a food name, a serving size, and a number of calories. A text file is read which contains the calories contained in specific food items. From this data, an array of Food objects will be created and used to populate a combo box for user selection. The Food objects will also be used in calculating the balance calories for a given user on a given day.
    User input will be used to create User objects which will be user name, age, gender, height, weight, and Food Diary objects (composition). The Food Diary objects will consist of Date (composition), Food object (composition), number of servings, and a balance. Food Diary objects will consist of the activity on any given day (see text area in sample output screen below). All User objects are saved to a file as objects and can be retrieved on subsequent runs of the program.
    The program will calculate the number of calories the user is allowed per day to maintain the user�s current weight (see below for formula to use for this).
    BMRMen = 66 + (13.7 * weightPounds/2.2) + (5 * heightInches*2.54) - (6.8 * age)
    BMRWomen = 655 + (9.6 * weightPounds/2.2) + (1.8 * heightInches*2.54) - (4.7 * age)
    GUI CODE
    <code>
    import javax.swing.*;
    import java.awt.*;
    import java.awt.event.*;
    public class FoodDiaryGUI extends JFrame implements ActionListener {
    JLabel lblName, lblAge, lblWeight,lblHeight,lblFemale,lblMale,lblFood;
    JTextField txtName, txtAge, txtWeight,txtHeight;
    JButton btnSave, btnNewUser;
    JTextArea outputArea;
    JComboBox cbFood;
    int currentIndex=0, lastIndex=4;
    public FoodDiaryGUI()
    super ("Food Diary Calculator");
    lblName= new JLabel("Name: ");
    lblAge= new JLabel("Age: ");
    lblWeight= new JLabel("Weight(lbs): ");
    lblHeight= new JLabel("Height(inches): ");
    lblFemale= new JLabel("Female: ");
    lblMale= new JLabel("Male: ");
    lblFood= new JLabel("Choose a Food: ");
    txtName= new JTextField(15);
    txtAge= new JTextField(3);
    txtWeight= new JTextField(6);
    txtHeight= new JTextField(6);
    outputArea= new JTextArea(9,20);
    cbFood= new JComboBox();
    cbFood.setPreferredSize(new Dimension(100, 20));
    Container c = getContentPane();
    JPanel northPanel = new JPanel();
    northPanel.setLayout(new FlowLayout());
    btnSave= new JButton("SAVE");
    northPanel.add(btnSave);
    btnNewUser= new JButton("NEW USER");
    northPanel.add(btnNewUser);
    btnSave.addActionListener(this);
    btnNewUser.addActionListener(this);
    JPanel centerPanel = new JPanel();
    centerPanel.setLayout(new FlowLayout());
    centerPanel.add(lblName);
    centerPanel.add(txtName);
    centerPanel.add(lblAge);
    centerPanel.add(txtAge);
    centerPanel.add(lblWeight);
    centerPanel.add(txtWeight);
    centerPanel.add(lblHeight);
    centerPanel.add(txtHeight);
    centerPanel.setLayout(new FlowLayout());
    JRadioButton rbMale = new JRadioButton(maleString);
    birdButton.setMnemonic(KeyEvent.VK_M);
    birdButton.setActionCommand(maleString);
    birdButton.setSelected(true);
    JRadioButton rbFemale = new JRadioButton(femaleString);
    catButton.setMnemonic(KeyEvent.VK_F);
    catButton.setActionCommand(femaleString);
    //Group the radio buttons.
    ButtonGroup group = new ButtonGroup();
    group.add(rbMale);
    group.add(rbFemale);
    //Register a listener for the radio buttons.
    rbMale.addActionListener(this);
    rbFemale.addActionListener(this);
    public void actionPerformed(ActionEvent rb) {
    picture.setIcon(new ImageIcon("images/"
    + rb.getActionCommand()
    + ".gif"));
    radioGroup.add(rbMale);
    radioGroup.add(rbFemale);
    centerPanel.add(rbMale);
    centerPanel.add(rbFemale);
    centerPanel.add(lblFood);
    centerPanel.add(cbFood);
    JPanel southPanel = new JPanel();
    southPanel.setLayout(new FlowLayout());
    southPanel.add (outputArea);
    c.add(northPanel,BorderLayout.NORTH);
    c.add(centerPanel,BorderLayout.CENTER);
    c.add(southPanel,BorderLayout.SOUTH);
    setSize(650,300);
    setVisible(true);
    //add listener to button components.
    public void actionPreformed(ActionEvent e)
    if (e.getSource()==btnSave)
    currentIndex++;
    currentIndex--;
    public static void main (String[] args)
    FoodDiaryGUI application = new FoodDiaryGUI();
    application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    public void actionPerformed(ActionEvent arg0) {
    // TODO Auto-generated method stub
    </code>
    THE .txt file is as:
    1000 ISLAND, SALAD DRSNG,LOCAL*1 TBSP*25
    1000 ISLAND, SALAD DRSNG,REGLR*1 TBSP*60
    100% NATURAL CEREAL *1 OZ*135
    40% BRAN FLAKES, KELLOGG'S*1 OZ*90
    40% BRAN FLAKES, POST*1 OZ*90
    ALFALFA SEEDS, SPROUTED, RAW*1 CUP*10
    ALL-BRAN CEREAL*1 OZ*70
    ALMONDS, WHOLE*1 OZ*165
    ANGELFOOD CAKE, FROM MIX*1 PIECE*125
    APPLE JUICE, CANNED*1 CUP*115
    i hope this forum site has to many java professionals and this problem is nothing for them. for me it is great.

    Stick to using a single userid and a single posting of a question:
    http://forum.java.sun.com/thread.jspa?threadID=731264&tstart=0

  • Example of Serialized objects and non-Serialized objects

    Hi,
    Can you please tell me some of eample of Serialized objects and nonserialized objects in java and j2ee.
    Thanks
    alex.

    sravan123 wrote:
    Serialised objects are File ,all Collection classes , subclasses of Throwable and subclasses of Number.
    Non-Serialised objects are Connection,DataSourrce,Resultset , Thread and MathYou forgot to log in as another user before answering your own question incorrectly for reasons I'm currently unable to fathom

  • Weblogic 8.1/Oracle 9 Writing and Reading Clob

    I’m trying to write and read a clob to a database table. The database table has
    an Id field (int) and a Content field (clob).
    My environment consists of Weblogic 8.1, and Oracle 9. Is there a way to get a
    handle to a Weblogic connection to Oracle and then write and read clobs?
    Any help would be greatly appreciated!
    Thanks,
    Mike

    Problem 1. US7ASCII and Linux - Status Resolved.
    The issue with the BEA 817 JDBC driver not connecting to the US7ASCII database tuned out to be that it had not deployed the connection pool correctly from the weblogic admin console... or that it was reported as being deployed when in fact it was not. After re-deploying the connection pool and restarting the server we were able to connect.
    The patch was for character sets was not needed.
    Problem 2. Oracle Stored Proc error.
    The problem with the stored procedures tunred out to be with ref cursors. A patch in sp3, and a change to the way we called the stored proc allowed us to fix the problem.
    The problem is reproduced when connecting to an Oracle 8.1.7 server.
    It was introduced in the Connect JDBC driver build 3.0.0007. According
    to the jdbcread.me file which comes with the 3.0.0007 build we
    deprecated the refCursorSupport connection property. This could be
    related to the driver not being able to execute a stored procedure
    containing ref cursors.
    Resolution
    Driver was fixed in the Connect JDBC 3.1 Oracle driver version 3.1.0008
    The trick was to use
    "{call PROC(?,?)}"
    instead of
    "BEGIN PROC(?, ?);
    END;"
    Here is a very useful link on the matter:
    http://groups.google.com/groups?hl=en&lr=&ie=UTF-8&threadm=b860627b.0405130528.4db317a0%40posting.google.com&rnum=1&prev=/groups%3Fq%3D%255BBEA%255D%255BOracle%2BJDBC%2BDriver%255DInvalid%2Bparameter%2Bbinding%26hl%3Den%26lr%3D%26ie%3DUTF-8%26selm%3Db860 27b.0405130528.4db317a0%2540posting.google.com%26rnum%3D1
    The bea type 4 is an oem from DataDirect
    http://knowledgebase2.datadirect.com/kbase.nsf/26536a530e20a22b85256e550079afc2/b3be8f8fcb7c30c285256c9f006f8645?OpenDocument&Highlight=0,oracle

  • Writing and reading data from a form

    I am trying to write a save and load feature for an application using mostly Jtextboxes and things. Basically I have a form that the user enters data into. I want to be able to save this data and load this data. I am relatively new to working on a GUI and I'm not quite sure if my knowledge of I/O applies to this. This is my stab at it but if I am completely off I would not be surprised. I don't want to print it to the command line but this was all I could think of right now. Any help would be greatly appreciated.     
    private void SavePrefs() {
              File SavePrefs;
              // get filename:
              fc.setDialogTitle("Select Filename For Site Data");
              int result = fc.showOpenDialog(f);
              if (result == JOptionPane.OK_OPTION) {
                   SavePrefs = fc.getSelectedFile();
                   // default file extension ".CMM"
                   if (!SavePrefs.getName().endsWith(".CMM")) {
                        // filename does not meet requirmeents:
                        System.out.println("NO CMIMS in filename");
                        SavePrefs = new File(SavePrefs.getAbsolutePath() + ".CMM");
                   // continue with save code:
                   System.out.println("File Selected:" + SavePrefs.toString());
                   //Creates a .cmm file with a code in it containing the data from the first site tab.
                   FileOutputStream out; // declare a file output object
    PrintStream p; // declare a print stream object
                   try
    // Create a new file output stream
    out = new FileOutputStream(SavePrefs.toString());
    // Connect print stream to the output stream
    p = new PrintStream( out );
    p.print(_SitePropPanel);
    p.close();
    catch (Exception e)
    System.err.println ("Error writing to file");
                   JOptionPane.showMessageDialog(null,
                             "File is saved.");
              // not OK selected (cancel or.?)
         private void LoadPrefs() {
              File loadPrefs;
              // get filename:
              fc.setDialogTitle("Select Filename For Site Data");
              int result = fc.showOpenDialog(f);
              if (result == JOptionPane.OK_OPTION) {
                   loadPrefs = fc.getSelectedFile();
                   // default file extension ".CMM"
                   if (!loadPrefs.getName().endsWith(".CMM")) {
                        // filename does not meet requirements:
                        System.out.println("NO CMIMS in filename");
                   // continue with save code:
                   System.out.println("File Selected:" + loadPrefs.toString());
                   try
         // Open the file that is the first
         // command line parameter
         FileInputStream fstream = new
                                  FileInputStream(loadPrefs.toString());
         // Convert our input stream to a
         // DataInputStream
                             DataInputStream in =
         new DataInputStream(fstream);
         // Continue to read lines while
         // there are still some left to read
         while (in.available() !=0)
         // Print file line to screen
                                  System.out.println (in.readLine());
                             in.close();
         catch (Exception e)
                             System.err.println("File input error");
              JOptionPane.showMessageDialog(null, "Feature is not yet implemented.");
         }

    Oh and the GUI is a window with menus where the save feature resides, but the data is in tabbed panels. That is where the _SitePropPanel comes in. I know I want it to write the input from the panel and not the panel. What would would I use for that? I tried getInputContext().                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                           

  • Runtime.exec("Perl Script writing and reading on I/O"), handling Streams

    Hi all !!
    In a first place : sorry for my english if it's not really understandable but I try to do as good as possible !
    I'm writing a GUI with Swing that will allow (in one of my multiple tables) the user to run a Perl Script.
    This Perl Script ask the user to choose a Folder ... then read all the files in this folder and for each file (xml File), extract the datas and put them in a database. But when a file that has to be inserted in the database contains this line : <Template_Used name="ST1.mtt"> and if the Template table in my database doesn't have the "ST1.mtt" stored ... the Perl Script ask to the user to give him the path of the file "ST1.mtt" so that the script can put the "ST1.mtt template" datas in the database.
    This script runs well when it is from a windows console.
    But I need a graphic interface !!!
    So I created a JButton "Process a folder".
    When the button is pressed, a JFileChooser appears and ask the user which Folder has to be processed.
    Then a Process is created with the command : ("cmd.exe /C \"C:\\Program Files\\Fluke\\Ansur\\ProcessFolder.bat\").
    The BatFile :
    {code}cd C:\Documents and Settings\tsd\Desktop\Gael-Project\Project_Files
    perl Process.pl
    exit{code}
    At this moment everything is working well.
    But my Process.pl (which is 300 lines long ... and that you don't even want to hear about), ask in a first time the Path of the folder to process and sometimes ask the path to a file (a template file).
    So I need to read and wirte on the STDIN/STDOUT during the exec of the Process.
    In order to handle this I created two different threads : one reading the Process.getInputStream with a BufferedReader and one other writing on the Process.getOutputStream with a PrintWrinter.
    What I need to do is :
    When I read a line from the InputStream saying "I need the path of the ST1.mtt file", I should run a JFileChooser ... the user find the file in the computer ... and I write in the OutputStream the path of the file, so that my Perl Script doesn't have un Unitialised value on <STDIN> and can continue to process !!
    I'm pretty sure it's possible ... because at the moment I just used a trick :
    When the user push the "process a folder" button, I write the paths in the OutputStream before than the script needs it and it works !
    But I need to write in the OutputStream only when it is time !!!
    Any idea ??
    Here are some parts of my code :
    {code}
    String filename = File.separator+"tmp";
              JFileChooser fc = new JFileChooser(new File(filename));
              fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY );
              // Show open dialog; this method does not return until the dialog is closed
         fc.showOpenDialog(null);
         Folder = fc.getSelectedFile();
              new GoodExec(cmd);
    {code}
    {code}
    public class GoodExec {
         public static Process proc;
         public static StreamGobbler errorGobbler;
         public static StreamGobbler inputGobbler;
         public static StreamGobbler outputGobbler;
         public GoodExec(String cmd)
         try
                   Runtime rt = Runtime.getRuntime();
              proc = rt.exec(cmd);
         // any error message?
         errorGobbler = new
         StreamGobbler(proc.getErrorStream(), "ERROR");
         // any input?
         inputGobbler = new
         StreamGobbler(proc.getInputStream(), "INPUT");
         // any output?
              outputGobbler = new
              StreamGobbler(proc.getOutputStream(), "OUTPUT");
         // kick them off
         errorGobbler.start();
         inputGobbler.start();
         outputGobbler.start();
         // any error???
         int exitVal = proc.waitFor();
         System.out.println("ExitValue: " + exitVal);
         } catch (Throwable t)
         t.printStackTrace();
    {code}
    {code}
    public class StreamGobbler implements Runnable
    InputStream is;
    OutputStream os;
    String type;
    Thread thread;
    public static String chaine;
    StreamGobbler(InputStream is, String type)
    this.is = is;
    this.os=null;
    this.type = type;
    StreamGobbler(OutputStream os, String type)
    this.os = os;
    this.is=null;
    this.type = type;
    public void start () {
         thread = new Thread(this);
         thread.start ();
    public void run()
    try
    if (is == null){
         PrintWriter toProgram = new PrintWriter(os);
         File FolderToProcess = ProcessFolder.Folder;
    String Folder = FolderToProcess.getPath();
    toProgram.write(Folder);
    toProgram.close();
    else {
         if (os == null){
         InputStreamReader isr = new InputStreamReader(is);
    BufferedReader br = new BufferedReader(isr);
    String line=null;
    String comp = "Please enter the exact path of the directory that contains the files you want to process.";
    while ( (line = br.readLine()) != null){
         if (type.equals("INPUT")){
              chaine+=line+"\n";
         if (line.equals(comp)) {
              System.out.println("give directory");RUN A JFILECHOOSER AND GIVE THE DIRECTORY TO THE OUTPUTSTREAM
    System.out.println(type + ">" + line);
    is.close ();
    catch (IOException ioe){
         ioe.printStackTrace();
    {code}
    And here is an example of a simple perl script that could be used (it s a simple one !!) :
    {code}
    #!/usr/bin/perl -w
    use strict;
    print "Please enter the exact path of the directory that contains the files you want to process.\n";
    my $dir= <STDIN>;
    chomp ($dir);
    print "titallala $dir";
    if (the template of the file is not in the database){
    print "Please give me the template so that I can put it in the database";
    $dir= <STDIN>;
    chomp ($dir);
    {code}
    Thank you for your help ... if it's possible to help me !!
    Gael

    BalusC -- The line that gives me my NullPointerException is when I call the "DisplayProduct()" method. Its a dumb question, but with NetBeans how do I find out which reference could be null? I'm not very familiar with how NetBeans works with finding out how to debug. Any help you can give me would be greatly appreciated.The IDE is com-plete-ly irrelevant. It's all about the source code.
    Do you understand anyway when and why a NullPointerException is been thrown? It is a subclass of RuntimeException and those kind of exceptions are very trival and generally indicate an design/logic/thinking fault in your code.
    SomeObject someObject = null; // The someObject reference is null.
    someObject.doSomething(); // Invoking a reference which is null would throw NPE.

  • Help required in writing And Reading Xml From Database

    Hi
    i m new to java.
    i m facing problem while writing Xml file from Mysql Database in java i m using the WebRowSet
    and also for Reading WebRowSet
    after reading the Xml i have to save this in Database
    (required source code)
    is there any one to help me in this way
    regards
    aamir

    shadab_think_globally wrote:
    {noformat}*hi everybody,
    please send me a ajax with jsp application
    suppose i enter a word in text area ajax will populate/suggest all string from database ,who started
    from that entering character(s).like a google string search.
    please send full source code
    *{noformat}how about you do it yourself?

  • Generate and read serial numbers...

    Hi all
    I'm trying to produce a system where we lock a projector's
    usage down to an individual. I'm intending to use the individual's
    email address, combined with their hard disk serial number and
    encoded to produce a serial number which can be quickly checked at
    run time. The serial number would be generated at our end
    (possibly) and emailed to the user.
    Has anyone got any hints on how to do this easily, before I
    get bogged down in trying to create my own algorithms and such?
    I would be happy to use a 3rd party extra...
    Thanks
    Flea

    Chunick wrote:
    > see my post to the same question you asked at
    www.director-online.com... and I
    > had to 'bog' myself down with researching the subject
    and writing my own
    > algorithms, but I'll tell you, it was fun and
    challenging to learn and
    > broadened my knowledge base immensely.
    Can you post the URL of your Director Online question? I just
    had a look there and
    couldn't find it.
    I came a cross a program called Licence Protector.
    http://www.mirage-systems.de/403.html
    There's also a Multimedia Edition
    http://www.mirage-systems.de/829.html
    It claims to be able to protect Flash, Video, Music, Images
    and text and Director
    files, allowthing like seial number access, limited trail
    versions, activation..
    Has a demo Director prpject donload. I haven't tried it out
    fully but intend to.
    regards
    Dean
    Director Lecturer / Consultant
    http://www.fbe.unsw.edu.au/learning/director
    http://www.multimediacreative.com.au

  • Dialog Instance writing and reading from wrong global directory

    Hi,
    I have just completed a HA installation of ECC 6 on a Windows 2008 cluster. On node B we have the CI installed and on node A we have an additional DI installed. The installation drive for these local instances is the I drive in both cases. The ASCS instance is installed on the clustered N drive.
    For some reason when a job runs on the Dialog Instance installed on node A it writes it log file to the I:\usr\sap\<SID>\SYS\global\100JOBLG directory rather that to the
    <sap cluster hostname>\sapmnt\<SID>\SYS\global\100JOBLG directory (which would equate to N:\usr\sap\<SID>\SYS\global\100JOBLG). Similarly when I try a read a job log from the DI on node A it tries to read from I:\usr\sap\<SID>\SYS\global\100JOBLG and when it can find the log it gives an error.
    If anybody has any ideas as to how I can reconfigure the instance to read and write to the correct directory that would be much appreciated.
    Cheers,
    Greg.

    Have you set a different SAPGLOBALHOST or DIR_GLOBAL in your instance profile?
    Kind regards,
    Mark

  • Japanese fonts and writing and reading in all lang...

    Could you address me to a better nokia forum where developers could read my posts?
    Nokia messaging is very old, old T9 never updated.
    old text messanging, no html
    old only text messaging: no pictures, photos emoticons emoji (so japanese stopped buying nokia)
    And most of all: only old ascii text. We can read only alphabet no russian or greek or chinese or japanese....
    and also some new mobile phone has some other fonts we cannot write in not alphabet language.
    I need Japanese and i have to buy for 79 euro a program for Psiloc, my sister need Russian but no european nokia has russian.
    So for new mobile phones Nokia think to use unicode character set? [or give it only to Hong kong phone, and delete the not alphabet charaters for europeans??)
    And most of I'd like to can write in japanese without install other software.
    I'd like to buy the new N97 but 650 euros for only alphabet and simple email text is too much

    It's possible to add fonts to some Nokia smartphones to display characters from other languages (including asian).
    But Nokia care center doesn't know about it.
    Unfortunately, add new input method is very difficult and required hacking phones.
    To add specific font in your Symbian smartphone
    1) insert SD card in computer 
    2) create folder "\resource\Fonts" on SD card
    3) Create TTF files wich contain characters for your language(s), 
    copy the font files with names S60SNRb.ttf and S60ZDIGI.ttf to this folder.
    4) insert SD card  to your phone and reboot
    Original TTF files you can take from C:\resourece on your phone (by 3rd part file manager)
    It works for me on Nokia E71

  • Read serialized objects : cannot read past first object :  StreamCorrupted

    I have written multiple instances of an object to a file. When I try to read them back, the first one works but the second gets a StreamCorruptedException: Type code out of range, is -84.
    Several Forum topics deal with this, but I have found no relevant replies.
    Thanks for any help.
    Here is the code:
    public void abFileWrite(AbRec abRec) throws IOException
    FileOutputStream fileStream = new FileOutputStream(abDFileName,true);
    ObjectOutputStream writer = new ObjectOutputStream(fileStream);
    try
    writer.writeObject((AbRec) abRec);
    writer.flush();
    fileStream.close();
    writer.close();
    catch (IOException ioe)
    System.out.println("abFile cannot write to file "+
    directory+abFileName+". "+"ex="+ioe);
    public void readAll()
    try{      // just TRY to read that second record!
    FileInputStream file = new FileInputStream(abDFileName);
    ObjectInputStream in = new ObjectInputStream(file);
    AbRec ar = (AbRec) in.readObject();
    System.out.println("1 ar="+ ar.getAb());
    ar = (AbRec) in.readObject(); //StreamCorruptedException: Type code out of range, is -84
    System.out.println("2 ar="+ ar.getAb());
    in.close();
    catch (Throwable th) { System.out.println("readAll th="+th);  }
    public class AbRec implements java.io.Serializable
    String ab;
    public AbRec(){}
    public void setAb (String a){ab = a;}
    public String getAb(){return (ab);}
    }

    The answer, thanks to Bass345, is:
    4 bytes of header info is stored each time.
    So, call skip on the FileInputStream.
    fileInputStreamName.skip((long)4);
    Note it is the FileInputStream, not the ObjectInputStream.

  • Mac pro 13'' harddisk makes noises when writing and reading data, but Techtool scanning result shows no bad blocks in the disk, that is normal?

    I bought my Mac pro 13 inch, i7 processor and 750G storage 20th November 2012. But I found when copy into or out the Mac, the harddisk makes noises, like bitting something. I thought there are bad blocks in the disk, but the result of Techtool scanning is no bad blocks in disk, and giving a passed conclusion.
    I went the apple store for testing, and the repairmen told me there are two choices available for me:1) replace the harddisk 2) back to the store i bought machine from for a new one. i think that the machine only bought few days, it had better not be disassembled, so i went back for a new one. unfortunately, the new one makes more noises than my old one. i don't know why like apple named brands notebooks have such problems.  did you undergo this experience ?

    All of the HDDs, be they in my MBPs or enclosures are barely audible.  I would say the you deserve no less.  I suggest that you do not leave until you are satisfied with a near silent HDD.
    Why you got two in a row is a puzzle, but then some people beat the odds and win the lottery.  In your case the results are not exactly positive.  All HDDs eventually fail, and some fail sooner than others.  At least you should start with a quiet one.
    Good luck.
    Ciao.

Maybe you are looking for

  • Creating a folder results in "no space left on device"?

    Hi again, today I encountered the following problem: trying to create a folder on one of my Xsan volumes resulted in a "no space left on device" error, although there are still 3.81 TB available. I also tried copying a disk image of 160 MB to the vol

  • Problem with Navigation Attributes when upgrading from BI 3.1 to BI 7.0

    Hello, I have the following problem that occured regarding queries during the upgrade from BI 3.1 to BI 7.0: As far as the queries are concerned it is not possible in the 7.0 system to completely rebuild them according to the queries in 3.1. More spe

  • Screen displaying negative image

    My 3 year old was hitting buttons on my laptop, I walked over to remove him and my screen is a complete negative image of what is being displayed. I am sure it was just a combination of buttons hit but I have no idea how to revert it. Anyone??? Anyon

  • Retina iMac Display doesn't turn on

    Hi guys, my new iMac just arrived. I unpacked it, put it on my desk and turned it on... The "turn-on"-sound was there, but the display is blinking just for a second on, and then it turns off - a few seconds later it turns for a moment on and then it

  • Won't export photos

    When I try to export photos from iPhoto to my desktop I get the message "unable to create/users/name/desktop" no matter what settings I use in the export window. My intent is not to create a backup but rather to create copies that use the photo's tit