Solved

Problems with loading text file into array of objects fields

Posted on 2011-09-15
6
330 Views
Last Modified: 2012-05-12
I would like to use a design pattern I wish to reuse when I create an array of class  instances
from extracted information from a loaded text file.

This program will parse a text file and load an array of objects
(private fields of NetInformationData  type objects) with the parsed data.

The fields of DataClass objects are of String and of ArrayList<String> type.

It will also print the data contained in the fields from the array of DataClass
objects to the console.


A typical data record in the text file is in the following format:

                Netname: <netname>      
                <pin1Name> <pin2name> <pin3Name> <pin4Name>
                -------------------------------------

Where the dashes line works as a delimiter for the record, the line starting with the
'Netname:' string indicates a start of each record. See attached input file: InputText.txt

The problem is, that even though the text file is parsed correctly (see first section
of output captured in 'PrintOutput.txt' file)  when the capture data is getting
printed out as the accessed fields of the array of objects the ArrayList fields are
ALWAYS the same as the ones for the last record.The pins information saved in the ArrayList and transferred over to NetInformationData instances gets lost somehow:

<pin1Name> <pin2name> <pin3Name> <pin4Name>  as part of the LAST record:

Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78

I think there is probably just some minor flaw with my program.
The program is running, and almost working.

Could you tell me / correct what it is?

Thank you.

Attila

P.S. I also noted that this program is quite a memory hog for some reason.
especially running on a larger input file with more objects created.

Can I do something to make this saving to an array of objects better?

Files included:

ReadTextFileLoadArrayOfObjects.java           main class
NetInformationData.java                                   class defining data type for storing records
InputText.txt                                                     input text file
PrintOutput.txt                                                  output running program
package readtextfileloadarrayofobjects;

import java.io.BufferedReader;
import java.io.DataInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.StringTokenizer;
import javax.swing.JOptionPane;

// This program will parse a text file and load an array of objects
// (private fields of NetInformationData  type objects) with the parsed data
// The fields of DataClass objects are of String and of ArrayList<String> type.
// It will also print the data contained in the fields from the array of DataClass objects
// to the console.

// Possible examples:
// http://www.dreamincode.net/forums/topic/163322-store-a-text-file-into-array-of-object/
// Input file format example:

            /*  Format of data in file:
                Netname: 01061055E_CPLD_T1_BIT      
                01061055E_CPLD_J3.44  01061055E_CPLD_U5.AA9  01061055E_CPLD_J204.32  
                -------------------------------------
             */

public class ReadTextFileLoadArrayOfObjects {
    
    // It is the 
    private static int numberOfNetInformationData =0;
    
    // make an array that contains single net information data object:
    private static NetInformationData[] netInformationDataArray  = new NetInformationData[1];
    
    
    public static void main(String[] args) {
        
        // Create an instance of this class
        ReadTextFileLoadArrayOfObjects readTextFileLoadArrayOfObjects = new ReadTextFileLoadArrayOfObjects();
        
        // call the method reading file contents to be saved into an array of objects
        String inputTextFile = "InputText.txt";
        
        boolean fileRead = loadTextFile(inputTextFile);
        
            if(fileRead){
                JOptionPane.showMessageDialog(null, "File Read", "Info Message", JOptionPane.INFORMATION_MESSAGE);
            }
        
        showCapturedInformation();
        
    }
    
    // Method for loading text file:
    public static  boolean loadTextFile(String inputFileName) {

        // Data loaded successfully
        boolean dataLoaded = false;
        
        // Variable holding the net name of currently processed net:
        String strCurrentNetName = "";
        
        // Create a new empty arraylist to hold pins information for use
        // with adding a new instance of NetInformationData to array of 
        // NetInformationData class instances.
        ArrayList<String> pinsWithNet = new ArrayList<String>();
        

        // Load the modified XNF netlist file:
        try {

        // Open the file
        FileInputStream fstream = new FileInputStream(inputFileName);
        // Get the object of DataInputStream
        DataInputStream in = new DataInputStream(fstream);
        BufferedReader br = new BufferedReader(new InputStreamReader(in));
        String strLine;
            
        
            
        //Read File Line By Line and feed it to StringReader instance
        while ((strLine = br.readLine()) != null) { 
            
            // Process individual lines as they are loaded from file.
            // Extract individual nets and pins information from each individual line.
            
            if (strLine.contains("Netname:")) // this is the first line of any new record, new record needs to be added to array if this is found
                    {
            
                        // Delete all information in pinsWithNet arraylist prior to creating a new instance
                        // of NetInformationData class, because pinsWithNet will have to be used empty with the constructor.
                        pinsWithNet.clear();
                        
                        // Extract netname portion from line:
                        // (The +1 below is for going to the next character after ':')
                        strCurrentNetName = (strLine.substring(strLine.indexOf(":")+1, strLine.length())).trim();
                        numberOfNetInformationData++;
                        
                         System.out.println("Net(" + numberOfNetInformationData + ")= " + strCurrentNetName);
                        
                        // Create a TEMPORARY array of NetInformationData instances with the 
                        // increased number of elements by ONE: numberOfNetInformationData pieces of data
                        NetInformationData[] tempArray = new NetInformationData[numberOfNetInformationData];
                        
                        // copy old smaller array to increased size array:
                        System.arraycopy(netInformationDataArray, 0, tempArray, 0, netInformationDataArray.length);
                        netInformationDataArray = tempArray;    // set reference back to original array, now original array becomes
                                                                // referenced by the temporary array, which in effect increases the element count of original array by one.
                        
            
                        netInformationDataArray[numberOfNetInformationData-1] = new NetInformationData(strCurrentNetName, pinsWithNet);
                        // (Note that pinsWithNet is empty at this point, only strCurrentNetName has a valid data loaded)
                        
                        String savedNetName = netInformationDataArray[numberOfNetInformationData-1].getNetName();
                        
                        
                     }
            
            else // No need to create a new piece of data, just change the fields (attributes) of the last object in the array created
                 // with extracted pin data.
                    {
                        if (!(strLine.contains("------------"))) // If it is NOT a delimiter of records line that's currently loaded
                            {
                        
                            // Create tokens to be loaded to pinsWithNet out of current line:
                            StringTokenizer st = new StringTokenizer(strLine);
                            
                                while (st.hasMoreTokens()) {
                                            // add the next token to the arraylist containing the pins info to be saved
                                            pinsWithNet.add(st.nextToken());
                                }
                            
                        
                                        // Iterate through elements of ArrayList, just to see that data is captured TEST ONLY +++++++++
                                        Iterator itr = pinsWithNet.iterator();
                                        System.out.println("Iterating through ArrayList elements...");
                                        while(itr.hasNext())
                                        System.out.println(itr.next()); 
                                        // +++++++++++++++++++++++++ END TEST ONLY ++++++++++++++++++++++++++++++++++++++++++++++++++++
                    
                    
                              //    Problem is here:   (!!!!!!!!!!!)
                        // Save arraylist in the object array to the last element of the object array:
                        netInformationDataArray[numberOfNetInformationData-1].setPinsWithNet(pinsWithNet);  
                        
                            }
                        else  // Contains "---------" delimiter, which is after the last line in each record
                            {
                                       System.out.println("Info for net Net(" + numberOfNetInformationData + ")= '"  + strCurrentNetName + "' has been extracted");
                                       dataLoaded = true; // If there is at least ONE piece of data could be extracted
                            }
                
                    }  
            
        }    

            } catch (Exception e) { //Catch exception if any
                JOptionPane.showMessageDialog(null, "Error: " + e.getMessage(),
                                      "File Read Error Program will terminate.", JOptionPane.ERROR_MESSAGE);
                System.exit(1); // exit with error
                }

        // Process file line-by-line end
        // At this point the input file is loaded into the array of objects
        
        return true;
            }
    
    
    private static void showCapturedInformation(){

        // Printing out captured data ++++++++++++++++++++++++++++++++++++++++++++++++++++++
        System.out.println("======================================================");
        for(int j=0; j<netInformationDataArray.length;j++){
                System.out.println("netInformationDataArray[" + j+ "].getNetName()=" + netInformationDataArray[j].getNetName());
            
                Iterator itr = netInformationDataArray[j].getPinsWithNet().iterator();
                    while (itr.hasNext())
                        System.out.println("Next pin: " + itr.next());   
                System.out.println("=================================="); 
    }
    
  }

}

Open in new window

package readtextfileloadarrayofobjects;

import java.util.ArrayList;

public class NetInformationData {
    
    // Constructor for creating an instance with intitialized data:
    public NetInformationData(String nName, ArrayList<String> pwNet){
        netName = nName;
        pinsWithNet = pwNet;
    }
    
    private String netName="";
    private ArrayList<String> pinsWithNet = new ArrayList<String>();
    
// Getters and setters for fields:
    
    public String getNetName(){
        return netName;
    }

    public ArrayList<String> getPinsWithNet(){
        return pinsWithNet;
    }
    
    public void setNetName(String nName){
        netName = nName;
    }
    
    public void setPinsWithNet(ArrayList<String> pwNet){
        pinsWithNet = pwNet;
    }
    
    
}

Open in new window

Netname: +1_8V
J1C.2  C7.1  HH1.1  U1.81  U1.17  U1.49  U1.112  C23.1  TP1.1  C6.1  VR1.2  VR1.3  C25.1  C21.1  C22.1  C24.1  arm_U1A.17  arm_U1A.49  arm_U1A.81  arm_U1A.112  arm_U1.17  arm_U1.49  arm_U1.81  arm_U1.112  
-------------------------------------
Netname: VGND      
J1C.23  J1C.4  J1C.1  C7.2  U1.16  U1.48  U1.82  U1.113  C23.2  C6.2  VR1.4  C25.2  C21.2  C22.2  C24.2  J1A.22  J1B.19  HH2.1  HH3.1  TP2.1  J1D.20  arm_U1A.16  arm_U1A.48  arm_U1A.82  arm_U1A.113  arm_U1.16  arm_U1.48  arm_U1.82  arm_U1.113  
-------------------------------------
Netname: P3_6
J1C.5  U1.66  arm_U1A.66  arm_U1.66  
-------------------------------------
Netname: P3_7
J1C.7  U1.68  arm_U1A.68  arm_U1.68  
-------------------------------------
Netname: P3_5
J1C.3  U1.65  arm_U1A.65  arm_U1.65  
-------------------------------------
Netname: P0_0
J1C.6  U1.67  arm_U1A.67  arm_U1.67  
-------------------------------------
Netname: P0_1
J1C.8  U1.69  arm_U1A.69  arm_U1.69  
-------------------------------------
Netname: P0_2
J1C.10  U1.71  arm_U1A.71  arm_U1.71  
-------------------------------------
Netname: P0_3
J1C.16  U1.76  arm_U1A.76  arm_U1.76  
-------------------------------------
Netname: P0_4
J1C.18  U1.78  arm_U1A.78  arm_U1.78  
-------------------------------------

Open in new window

Net(1)= +1_8V
Iterating through ArrayList elements...
J1C.2
C7.1
HH1.1
U1.81
U1.17
U1.49
U1.112
C23.1
TP1.1
C6.1
VR1.2
VR1.3
C25.1
C21.1
C22.1
C24.1
arm_U1A.17
arm_U1A.49
arm_U1A.81
arm_U1A.112
arm_U1.17
arm_U1.49
arm_U1.81
arm_U1.112
Info for net Net(1)= '+1_8V' has been extracted
Net(2)= VGND
Iterating through ArrayList elements...
J1C.23
J1C.4
J1C.1
C7.2
U1.16
U1.48
U1.82
U1.113
C23.2
C6.2
VR1.4
C25.2
C21.2
C22.2
C24.2
J1A.22
J1B.19
HH2.1
HH3.1
TP2.1
J1D.20
arm_U1A.16
arm_U1A.48
arm_U1A.82
arm_U1A.113
arm_U1.16
arm_U1.48
arm_U1.82
arm_U1.113
Info for net Net(2)= 'VGND' has been extracted
Net(3)= P3_6
Iterating through ArrayList elements...
J1C.5
U1.66
arm_U1A.66
arm_U1.66
Info for net Net(3)= 'P3_6' has been extracted
Net(4)= P3_7
Iterating through ArrayList elements...
J1C.7
U1.68
arm_U1A.68
arm_U1.68
Info for net Net(4)= 'P3_7' has been extracted
Net(5)= P3_5
Iterating through ArrayList elements...
J1C.3
U1.65
arm_U1A.65
arm_U1.65
Info for net Net(5)= 'P3_5' has been extracted
Net(6)= P0_0
Iterating through ArrayList elements...
J1C.6
U1.67
arm_U1A.67
arm_U1.67
Info for net Net(6)= 'P0_0' has been extracted
Net(7)= P0_1
Iterating through ArrayList elements...
J1C.8
U1.69
arm_U1A.69
arm_U1.69
Info for net Net(7)= 'P0_1' has been extracted
Net(8)= P0_2
Iterating through ArrayList elements...
J1C.10
U1.71
arm_U1A.71
arm_U1.71
Info for net Net(8)= 'P0_2' has been extracted
Net(9)= P0_3
Iterating through ArrayList elements...
J1C.16
U1.76
arm_U1A.76
arm_U1.76
Info for net Net(9)= 'P0_3' has been extracted
Net(10)= P0_4
Iterating through ArrayList elements...
J1C.18
U1.78
arm_U1A.78
arm_U1.78
Info for net Net(10)= 'P0_4' has been extracted
======================================================
netInformationDataArray[0].getNetName()=+1_8V
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[1].getNetName()=VGND
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[2].getNetName()=P3_6
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[3].getNetName()=P3_7
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[4].getNetName()=P3_5
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[5].getNetName()=P0_0
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[6].getNetName()=P0_1
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[7].getNetName()=P0_2
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[8].getNetName()=P0_3
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
netInformationDataArray[9].getNetName()=P0_4
Next pin: J1C.18
Next pin: U1.78
Next pin: arm_U1A.78
Next pin: arm_U1.78
==================================
Process exited with exit code 0.

Open in new window

0
Comment
Question by:AttilaB
  • 3
  • 2
6 Comments
 

Author Comment

by:AttilaB
Comment Utility
I uploaded the files here that you see  in the code windows above  (AllCodeAndInputOutput.zip)
AllCodeAndInputOutput.zip
0
 
LVL 47

Accepted Solution

by:
for_yan earned 500 total points
Comment Utility
This will work correctly, I hope - try

package readtextfileloadarrayofobjects;

import java.util.ArrayList;

public class NetInformationData {

    // Constructor for creating an instance with intitialized data:
    public NetInformationData(String nName, ArrayList<String> pwNet){
        this.netName = nName;
       // this.pinsWithNet = pwNet;
        ArrayList<String> ar = new ArrayList<String>();

        ar.addAll(pwNet);
         pinsWithNet = ar;
    }

    private String netName="";
   private ArrayList<String> pinsWithNet;

// Getters and setters for fields:

    public String getNetName(){
        return netName;
    }

    public ArrayList<String> getPinsWithNet(){
        return pinsWithNet;
    }

    public void setNetName(String nName){
        netName = nName;
    }

    public void setPinsWithNet(ArrayList<String> pwNet){
          ArrayList<String> ar = new ArrayList<String>();
         ar.addAll(pwNet);
         pinsWithNet = ar;
      
    }


}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
Comment Utility

That was becaues you created this once in the very beginning:
  ArrayList<String> pinsWithNet = new ArrayList<String>();


then when you do this
  netInformationDataArray[numberOfNetInformationData-1].setPinsWithNet(pinsWithNet);  

you just assign the pointer to ArrayList inside different NetInformationData objects to the same address

so whatever happens to sit last in that ArrayList will effectively become the conatents of ArryList in all
objects of the array.

You need to craete new ArrayList on each iteration, or like I did
insode the set method cloned the ArrayList individually for ecach obejct


0
Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

 
LVL 47

Expert Comment

by:for_yan
Comment Utility
Just compare two cases below - this absolutely analogous to what
you experienced:

import java.util.ArrayList;

public class Miscellaneous {

    public static void main(String[] args) {

       
        ArrayList<StringBuffer> ar = new ArrayList<StringBuffer>();
       StringBuffer  s = new StringBuffer("1");
        ar.add(s);
        s.append("2");
        ar.add(s);
          s.append("3");
        ar.add(s);
         System.out.println(ar);



        ArrayList<StringBuffer> ar1 = new ArrayList<StringBuffer>();
          StringBuffer  s1 = new StringBuffer("1");
        ar1.add(s1);
       s1 = new StringBuffer("12");
        ar1.add(s1);
          s1 = new StringBuffer("123");
        ar1.add(s1);
         System.out.println(ar1);


        
    }

}

Open in new window


Result:
[123, 123, 123]
[1, 12, 123]

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
Comment Utility
The code is generally ok apart from that minor error but could be much simplified. Use fewer arrays and more List
0
 

Author Closing Comment

by:AttilaB
Comment Utility
A+ Solution!

Along with your explanations now I know what I was doing wrong.
Thank you for the detailed explanations as well.
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
changeXy challenge 13 56
pairstar challenge 2 41
Python Assistance 7 31
Securing Jmx Console and web console 2 45
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
In this post we will learn how to connect and configure Android Device (Smartphone etc.) with Android Studio. After that we will run a simple Hello World Program.
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…

763 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now