How to input data into an arraylist from a text file?

I am trying to take data from a text file and put that data into an arraylist. First here is the text file:
[item1, 10, 125.0, item2, 10, 12.0, item3, 20, 158.0]
3
4530.0
[item5, 65, 555.5, item4, 29, 689.0]
2
56088.5
[item7, 84, 34.5, item6, 103, 0.5, item8, 85, 1.36]
3
3065.1The text between the [ ] is the output from my arraylists. I have three arraylists. The first [ ] belongs to arraylist A, the second to arraylist B, and the third to arraylist C. The format of the arraylists is this:
<item name>,<# in stock>,<value of one item>
The first number below the arraylists in the text file represents the number of items in the list. The second number below the arraylists represents the total value of the items in the arraylists.
Here is the class file I have (yes, it does everything):
import java.io.*;
import java.util.Scanner;
import java.util.ArrayList;
public class Inventory extends Object
     public int toAdd = 0;
     private boolean done = false;               //Are we done yet?
     public String strItemName;                    //The name of the item type.
     public int intNumInStock;                    //The number in stock of that type.      
     public double dblValueOfOneItem;          //The value of one item.
    public String strNumberInStock;               
    public double dblTotalValueA;               //The total value of warehouse A.
    public double dblTotalValueB;               //The total value of warehouse B.
    public double dblTotalValueC;               //The total value of warehouse C.
    public int intWarehouseAItemCount;          //Counter for items in warehouse A.
    public int intWarehouseBItemCount;          //Counter for items in warehouse B.
    public int intWarehouseCItemCount;          //Counter for items in warehouse C.
     ArrayList warehouseAList = new ArrayList();     //Create the Warehouse A ArrayList.                                   
     ArrayList warehouseBList = new ArrayList(); //Create the Warehouse B arrayList.
     ArrayList warehouseCList = new ArrayList(); //Create the Warehouse C arrayList.
     /** Construct a new Inventory object. */
     public Inventory()
          super();
     /**Add items to the Warehouse A ArrayList.*/
     private void createWareHouseA()
          System.out.println("!" + toAdd + " item types will be added to warehouse A.");
          //Cast
          String strNumInStock = Integer.toString(intNumInStock);
          String strValueOfOneItem = Double.toString(dblValueOfOneItem);
          this.strNumberInStock = strNumInStock;
          System.out.println("!Initial size of warehouseAList :  " +
                                                            warehouseAList.size());
          //Add items to the array List
          warehouseAList.add(this.strItemName);
          warehouseAList.add(this.strNumberInStock);
          warehouseAList.add(this.dblValueOfOneItem);
          System.out.println("!size of arrayList after additions " + warehouseAList.size());
     /**Add items to the Warehouse B ArrayList.*/
     private void createWareHouseB()
          System.out.println("!" + toAdd + " item types will be added to warehouse B.");
          //Cast
          String strNumInStock = Integer.toString(intNumInStock);
          String strValueOfOneItem = Double.toString(dblValueOfOneItem);
          this.strNumberInStock = strNumInStock;
          System.out.println("!Initial size of warehouseBList :  " +
                                                            warehouseBList.size());
          //Add items to the array List
          warehouseBList.add(this.strItemName);
          warehouseBList.add(this.strNumberInStock);
          warehouseBList.add(this.dblValueOfOneItem);
          System.out.println("!size of arrayList after additions " + warehouseBList.size());
     /**Add items to the Warehouse C ArrayList.*/
     private void createWareHouseC()
          System.out.println("!" + toAdd + " item types will be added to warehouse C.");
          //Cast
          String strNumInStock = Integer.toString(intNumInStock);
          String strValueOfOneItem = Double.toString(dblValueOfOneItem);
          this.strNumberInStock = strNumInStock;
          System.out.println("!Initial size of warehouseCList :  " +
                                                            warehouseCList.size());
          //Add items to the array List
          warehouseCList.add(this.strItemName);
          warehouseCList.add(this.strNumberInStock);
          warehouseCList.add(this.dblValueOfOneItem);
          System.out.println("!size of arrayList after additions " + warehouseCList.size());
     /**Interpret the commands entered by the user.*/
     public void cmdInterpreter()
          this.displayHelp();
          Scanner cin = new Scanner(System.in);
          while (!this.done)
               System.out.print(">");
               //"line" equals the next line of input.
               String line = cin.nextLine();
               this.executeCmd(line);
     /**Execute one line entered by the user.
      * @param cmdLN; The command entered by the user to execute. */
      private void executeCmd(String cmdLN)
           Scanner line = new Scanner(cmdLN);
           if (line.hasNext())
                String cmd = line.next();
                //What to do when users enter the various commands below.
                if (cmd.equals("help"))
                     this.displayHelp();
                else if (cmd.equals("Q!"))
                     this.done = true;
                else if (cmd.equals("F") && line.hasNext())
                     this.inputFromFile(line.next());
                else if (cmd.equals("K") && line.hasNext())
                     int numItemsToAdd = Integer.valueOf( line.next() ).intValue();
                     this.toAdd = numItemsToAdd;
                     this.inputFromKeyboard(numItemsToAdd);
      /**What to do if input comes from a file.
       *     @param inputFile; The name of the input file to process.*/
      private void inputFromFile(String inputFile)
           Scanner cin = new Scanner(System.in);
           System.out.println("!Using input file " + inputFile + ".");
           System.out.print("!Enter the name of the output file: ");
           String outputFile = cin.next();
           System.out.println("!Using output file " + outputFile + ".");
          try
               BufferedReader in = new BufferedReader(new FileReader(inputFile));
               //Scanner in = new Scanner(new File(inputFile));
               //Initialize the String variables.
               String line1 = null;
               String line2 = null;
               String line3 = null;
               String line4 = null;
               String line5 = null;
               String line6 = null;
               String line7 = null;
               String line8 = null;
               String line9 = null;
               System.out.println(in.equals(",") + " see?");
               //System.out.println((char)(char)in.read() + " experiment");
               /**This loop assigns values to the string variables based on the
                * values on each line in the input file. */
               while(in.readLine() != null)
                    line1 = in.readLine();
                    line2 = in.readLine();
                    line3 = in.readLine();
                    line4 = in.readLine();
                    line5 = in.readLine();
                    line6 = in.readLine();
                    line7 = in.readLine();
                    line8 = in.readLine();
                    line9 = in.readLine();
               //Print the contents of each line in the input file.
               System.out.println("!value of line 1: " + line1);
               System.out.println("!value of line 2: " + line2);
               System.out.println("!value of line 3: " + line3);
               System.out.println("!value of line 4: " + line4);
               System.out.println("!value of line 5: " + line5);
               System.out.println("!value of line 6: " + line6);
               System.out.println("!value of line 7: " + line7);
               System.out.println("!value of line 8: " + line8);
               System.out.println("!value of line 9: " + line9);
            /**Add items to the warehouses.*/
               warehouseAList.add(line1);
               warehouseBList.add(line4);
               warehouseCList.add(line7);
            /**Add the item count and total value for warehouse A.*/
               int intLine2 = Integer.valueOf(line2).intValue();
               this.intWarehouseAItemCount = intLine2;
               double dblLine3 = Double.valueOf(line3).doubleValue();
               this.dblTotalValueA = dblLine3;
            /**Add the item count and total value for warehouse B.*/
               int intLine5 = Integer.valueOf(line5).intValue();
               this.intWarehouseBItemCount = intLine5;
               double dblLine6 = Double.valueOf(line6).doubleValue();
               this.dblTotalValueB = dblLine6;
            /**Add the item count and total value for warehouse C.*/
              int intLine8 = Integer.valueOf(line8).intValue();
              this.intWarehouseCItemCount = intLine8;
              double dblLine9 = Double.valueOf(line9).doubleValue();
              this.dblTotalValueC = dblLine9;
            /**Ask the user how many items to add or delete from inventory.*/
              System.out.print("Enter the number to add to inventory for " +
                                                           warehouseAList.get(0) + ":");
              String toAddOrDel = cin.next();
            /**Print the contents of all the warehouses. */
               System.out.println(" ");
               //Print the contents of warehouse A.
               System.out.println("!--------------------------------");
               System.out.println("!----------Warehouse A:----------");
               System.out.println("!--------------------------------");
               //Print the item list for warehouse A.
               System.out.println(warehouseAList);
               //Print the total amount of items in warehouse A.
               System.out.println("Total items: " + this.intWarehouseAItemCount);
               //Print the total value of the items in warehouse A.
               System.out.println("Total value: " + this.dblTotalValueA);
               System.out.println("!--------------------------------");
               System.out.println("!----------Warehouse B:----------");
               System.out.println("!--------------------------------");
               //Print the item list for warehouse B.
               System.out.println("!warehouseB: " + warehouseBList);
               //Print the total amount of items in warehouse B.
               System.out.println("Total items: " + this.intWarehouseBItemCount);
               //Print the total value of the items in warehouse B.
               System.out.println("Total value: " + this.dblTotalValueB);
               System.out.println("!--------------------------------");
               System.out.println("!----------Warehouse C:----------");
               System.out.println("!--------------------------------");
               //Print the item list for warehouse C.
               System.out.println("!warehouseC: " + warehouseCList);
               //Print the total amount of items in warehouse C.
               System.out.println("Total items: " + this.intWarehouseCItemCount);
               //Print the total value of the items in warehouse C.
               System.out.println("Total value: " + this.dblTotalValueC);
               in.close();
          catch (FileNotFoundException e)
               System.out.println("!Error: Unable to open file for reading.");
          catch (EOFException e)
               System.out.println("!Error: EOF encountered, file may be corrupted.");
          catch (IOException e)
               System.out.println("!Error: Cannot read from file.");
      /**What to do if input comes from the keyboard.
       *     @param numItems; The total number of items that will be added to the
       *                      Warehouse(s). */
      public void inputFromKeyboard(int numItems)
           System.out.println("!You will be adding " + numItems + " items to " +
                                         "inventory from the keyboard. ");
           this.toAdd = numItems;
           Scanner cin = new Scanner(System.in);
           //Prompt user for name of output file.
           System.out.print("!Enter the name of the output file: ");
           String outputFile = cin.next();
           /**This loop asks the user for information about the item(s) and inputs
             *them into the appropriate array.*/
           int count = 0;
           while (numItems > count)
                //Item name.
                System.out.print("!Item name: ");
                String addItemName = cin.next();
                //Number in stock.
                System.out.print("!Number in stock: ");
                String addNumInStock = cin.next();
                //Initial warehouse.
                System.out.print("!Initial warehouse(A,B,C): ");
                String addInitWarehouse = cin.next();
                //Value of one item.
                System.out.print("!Value of one item: ");
                String addValueOfOneItem = cin.next();
                //Add or delete from inventory
                System.out.print("!Enter amount to add or delete from inventory: ");
                String strAddOrDelete = cin.next();
                System.out.println("!Amount to add or delete: " + strAddOrDelete);
                //Cast
                int intAddNumInStock = Integer.valueOf(addNumInStock).intValue();
                double doubleAddValueOfOneItem = Double.valueOf(addValueOfOneItem).doubleValue();
                int intAddOrDelete = Integer.valueOf(strAddOrDelete).intValue();
                /**Add intAddNumInStock with intAddOrDelete to determine the amount
                 * to add or delete from inventory (If a user wishes to remove items
                 * from inventory simply add negative values). */
                intAddNumInStock = intAddNumInStock + intAddOrDelete;
                System.out.println("!Inventory after modifications: " + strAddOrDelete);
                this.strItemName = addItemName;
                this.intNumInStock = intAddNumInStock;
                this.dblValueOfOneItem = doubleAddValueOfOneItem;
                //Put items into warehouse A if appropriate.
                if (intAddNumInStock < 25)
                    //Increment the warehouse A item count.
                    this.intWarehouseAItemCount = this.intWarehouseAItemCount + 1;
                    //Calculate the total value of warehouse A.
                    this.dblTotalValueA = this.dblTotalValueA + intAddNumInStock * doubleAddValueOfOneItem;
                    //Create the warehouse A array list.
                    this.createWareHouseA();
                //Put items into warehouse B if appropriate.
                if (intAddNumInStock >= 25)
                    if (intAddNumInStock < 75)
                         //Increment the warehouse B item count.
                         this.intWarehouseBItemCount = this.intWarehouseBItemCount + 1;
                         //Calculate the total value of warehouse B.
                         this.dblTotalValueB = this.dblTotalValueB + intAddNumInStock * doubleAddValueOfOneItem;
                         //Create the warehouse B array list.
                         this.createWareHouseB();
                //Put items into warehouse C if appropriate.
                if (intAddNumInStock >= 75)
                    //Increment the warehouse C item count.
                    this.intWarehouseCItemCount = this.intWarehouseCItemCount + 1;
                    //Calculate the total value of warehouse C.
                    this.dblTotalValueC = this.dblTotalValueC + intAddNumInStock * doubleAddValueOfOneItem;
                    //Create the warehouse C array list.
                    this.createWareHouseC();
                 //display helpful information.      
                System.out.println("!--------------------------------");
                System.out.println("!" + addItemName + " is the item name.");
                System.out.println("!" + addNumInStock + " is the number in stock.");
                System.out.println("!" + addInitWarehouse + " is the initial warehouse.");
                System.out.println("!" + addValueOfOneItem + " is the value of one item.");
                System.out.println("!--------------------------------------------------");
               //Increment the counters.
                count++;
           /**Create and write to the output file. */
           try
                 //Use the output file specified by the user.
                PrintWriter out = new PrintWriter(outputFile);
             /**Write warehouse A details.*/
                  //Blank the first line.
                  out.println(" ");
                //Write the array list for warehouse A.
                out.println(warehouseAList);
                //Write the amount of items in warehouse A.
                out.println(intWarehouseAItemCount);
                //Write the total value for warehouse A.
                out.println(dblTotalValueA);
             /**Write warehosue B details.*/
               //Write the array list for warehouse B.
                out.println(warehouseBList);
                //Write the amount of items in warehouse B.
                out.println(intWarehouseBItemCount);
                //Write the total value for warehouse B.
                out.println(dblTotalValueB);
             /**Write warehouse C details.*/
                  //Write the array list for warehouse C.
                out.println(warehouseCList);
                //Write the amount of items in warehouse C.
                out.println(intWarehouseCItemCount);
                //Write the total value for warehouse C.
                out.println(dblTotalValueC);
                //Close the output file.
                out.close();     
            catch (FileNotFoundException e)
               System.out.println("Error: Unable to open file for reading.");
           catch (IOException e)
               System.out.println("Error: Cannot read from file.");
           /**View the contents and the value of each warehouse.*/
           System.out.println("!---------------Inventory Summary------------------");
           System.out.println("!--------------------------------------------------");
           System.out.println("!--------------------LEGEND:-----------------------");
           System.out.println("!<item type>, <amount in stock>,<value of one item>");
           System.out.println("!--------------------------------------------------");
           System.out.println("!------------------Warehouse A:--------------------");
           System.out.println("!--------------------------------------------------");
           //Display Items in warehouse A.
           System.out.println(warehouseAList);
           //Total items in warehouse A.
           System.out.println("Total items: " + intWarehouseAItemCount);
           //Display total value of warehouse A.
           System.out.println("Total value: " + "$" + dblTotalValueA);
           System.out.println("!--------------------------------------------------");
           System.out.println("!------------------Warehouse B:--------------------");
           System.out.println("!--------------------------------------------------");
           //Display Items in warehouse B.
           System.out.println(warehouseBList);
           //Total items in warehouse B.
           System.out.println("Total items: " + intWarehouseBItemCount);
           //Display total value of warehouse B.
           System.out.println("Total value: " + "$" + dblTotalValueB);
           System.out.println("!--------------------------------------------------");
           System.out.println("!------------------Warehouse C:--------------------");
           System.out.println("!--------------------------------------------------");
           //Display Items in warehouse C.
           System.out.println(warehouseCList);
           //Total items in warehouse C.
           System.out.println("Total items: " + intWarehouseCItemCount);
           //Display total value of warehouse C.
           System.out.println("Total value: " + "$" + dblTotalValueC);
     /**Display a help message.*/
     private void displayHelp()
          System.out.println("!--------------------------------");
          System.out.println("! General Help:");
          System.out.println("!--------------------------------");
          System.out.println("! ");
          System.out.println("!'help' display this help message.");
          System.out.println("!'Q!' quit this program.");
          System.out.println("!--------------------------------");
          System.out.println("! Input File Specific Commands:");
          System.out.println("!--------------------------------");
          System.out.println("! ");
          System.out.println("!'F' <name> type F followed by the name of the " +
                                   "file to be used for input.");
          System.out.println("!---------------------------------------");
          System.out.println("! Input From Keyboard Specific Commands:");
          System.out.println("!---------------------------------------");
          System.out.println("! ");
          System.out.println("!'K' <number> type K followed by the number of " +
                                    "items that will be added. ");
          System.out.println("! ");
}Program file:
public class InventoryProg
     public static void main(String[] args)
          //Create a new Inventory object.
          Inventory test = new Inventory();
          //Execute the command interpreter.
          test.cmdInterpreter();
}Right now I am stuck on this and I cannot progress any further until I figure out how to input the data in the text file back into a arraylist.
Thanks in advance.

Thanks but I figured it out. Heres a sample of the code i used to solve my problem:
try
                       //Warehouse A BufferedReader.
               BufferedReader inA = new BufferedReader(new FileReader(inputFileWarehouseA));
               //Warehouse B BufferedReader.
               BufferedReader inB = new BufferedReader(new FileReader(inputFileWarehouseB));
               //Warehouse C BufferedReader.
               BufferedReader inC = new BufferedReader(new FileReader(inputFileWarehouseC));
               //Warehouse details BufferedReader.
               BufferedReader inDetails = new BufferedReader(new FileReader(inputFileDetails));
               //Will hold values in warehouse arraylists.
               String lineA = null;
               String lineB = null;
               String lineC = null;
               //Will hold the details of each warehouse.
               String line1 = null;
               String line2 = null;
               String line3 = null;
               String line4 = null;
               String line5 = null;
               String line6 = null;
               //Get the item count and total value for each warehouse.
               while(inDetails.readLine() != null)
                    line1 = inDetails.readLine();
                    line2 = inDetails.readLine();
                    line3 = inDetails.readLine();
                    line4 = inDetails.readLine();
                    line5 = inDetails.readLine();
                    line6 = inDetails.readLine();
           /**Assign the item count and total value to warehouse A.*/
              //Cast.
               int intLine1 = Integer.valueOf(line1).intValue();
               double dblLine2 = Double.valueOf(line2).doubleValue();
               //Assign the values.
               this.intWarehouseAItemCount = intLine1;
               this.dblTotalValueA = dblLine2;
            /**Assign the item count and total value to warehouse B.*/
                 //Cast.
               int intLine3 = Integer.valueOf(line3).intValue();
               double dblLine4 = Double.valueOf(line4).doubleValue();
                 //Assign the values.
               this.intWarehouseBItemCount = intLine3;
               this.dblTotalValueB = dblLine4;
            /**Assign the item count and total value to warehouse C.*/
                 //Cast.
                 int intLine5 = Integer.valueOf(line5).intValue();
               double dblLine6 = Double.valueOf(line6).doubleValue();
               //Assign the values.
               this.intWarehouseCItemCount = intLine5;
               this.dblTotalValueC = dblLine6;
            /**Put the items back into the warehouses arraylists. */
               //Add items to warehouse A.
               while((lineA = inA.readLine()) != null)
                    warehouseAList.add(lineA);
               //Add items to warehouse B.
               while((lineB = inB.readLine()) != null)
                    warehouseBList.add(lineB);
               //Add items to warehouse C.
               while((lineC = inC.readLine()) != null)
                    warehouseCList.add(lineC);
               }(this isn't the whole try statement its pretty long)

Similar Messages

  • How to put data into a hashtable from a text file

    I need some help to put the words in a text file to a hashtable.The text file
    consist of words and the following set of punctuation marks {, . ; : } and spaces.
    thanks in advance.

    Navy_Coder wrote:
    6 zebras.But you must marry his eldest daughter as well, for that dowry.

  • How to upload data into a database from a csv file in a jsp app?

    I can write a HTML form to let users to post a csv file and store it in the web server, then how could I process the file to load the data into a View Obj or an Entity Obj without manually parsing the csv files? Any jsp or java code samples that will do something like the "sqlload" in sqlplus?
    I'm using JDev 3.1.1.2. Thanks.

    Navy_Coder wrote:
    6 zebras.But you must marry his eldest daughter as well, for that dowry.

  • How to load data into an infocube from a flat file

    HI friends,
    Iam a learner of bw.
    I have master and transaction data to load into an info cube.
    I think we can load master data first, and then transaction data. that is master data we have to load through direct or flexible update and then transaction data through flexible update by preparing 2 excel sheets( one for master data and other for transaction data)
    Or
    can we load both at a time by preparing a single excel sheet which covers the values of characteristic, attributes and key figures.
    sai
    sai

    Hi Sai,
    Please find your replies below -
    I have master and transaction data to load into an info cube.
    >> You load master data in InfoObejcts and Transaction data in Cubes. So first Identify the Master data InfoObjects & InfoCubes<<
    I think we can load master data first, and then transaction data. << Yup good practice is to load master data first & then transaction data<<
    that is master data we have to load through direct or flexible update << you need to look into your scenario which one are you using??<<
    and then transaction data through flexible update by preparing 2 excel sheets( one for master data and other for transaction data) << Yup I think you will need separate file - Master data one for InfoObejcts data load & transcation data one for InfoCube data laod>>
    Or
    can we load both at a time by preparing a single excel sheet which covers the values of characteristic, attributes and key figures.
    Hope it helps
    Regards
    Vikash

  • How to input data into a table with columns?

    I am trying to input data into a table.  My table have 5 columns and an unlimited amount of rows.  I created a program in LabView that enters the data into the table but it enters all of the data in one row.  I would like to enter the first set of information into the first column, the second set of info into the second  column and so on.  I am including a copy of the program that I am working with.  I would like the number of runs to be put into the first column (it should count down like number 5 in first row, number 4 in second row, number 3 in third row, and so on).  I would like the applied voltage to be placed in the second column, and so on.  Any help or information will be greatly appreciated.  I am working with LabView Version 6.1 and 8.0.  I am submitting the vi from 6.1. 
    Attachments:
    FJ-PROGRAM.vi ‏68 KB

    Pondered,
    I looked at your code and I think you might be making things too complicated. I've included a very simple example that demonstrates how to write a 2D array of integers to a table. Hope you find this helpful. It is in LV 7.1.
    Chris C
    Chris Cilino
    National Instruments
    LabVIEW Product Marketing Manager
    Certified LabVIEW Architect
    Attachments:
    rows - columns.vi ‏17 KB

  • How to insert data into a table from an xml document

    using the XmlSql Utility, how do I insert data into a table from an xml document, using the sqlplus prompt.
    if i use the xmlgen.insertXML(....)
    requires a CLOB file, which i dont have, only the xml doc.
    Cant i insert directly from the doc to the table?
    the xmlgen examples I have seen first convert a table to a CLOB xmlString and then insert it into another table.
    Isnt there any other way?

    Your question is little perplexing.
    If you're using XML SQL Utility from
    the commandline, just use putXML.
    java OracleXML putXML
    null

  • How to load data into an ods from multiple info sources.

    hi all...
    i am given a task to load data into an ods from 3 infosources ...
    can someone plz give me the flow .
    thank u in advance..

    Hi Hara Pradhan,
    You have to create 3 update rules by giving the 3 different infosources while creating each update rule. And u have to create the infopackages under each infosource. with this u can load the data to the same data target from multiple info sources.
    Hope it helps!
    Assign points if it helps!

  • How to input data into Pdf file

    I am not too sure if I am posting my question in the right forum.
    I would like to know what version of Adobe acrobat can allow me to create a document, where clients can input data into it?
    Here is an online example
    http://www.uscis.gov/files/form/N-400.pdf
    Thanks.
    Oceans

    If your users will be using Reader and you want your users to be able to save the form or email it, you will need to apply 'Extended Form Rights' (version 8 Provessional or Version 9 Standard or better) and for signatures you will need to apply 'Signature Rights' using an Adobe server product.

  • HOW TO INSERT DATA INTO SQL SERVER FROM MS ACCESS TABLE??

    NEED TO INSERT DATA INTO SQL SERVER FROM MS ACCESS TABLE.

    this is another method
    http://www.mssqltips.com/sqlservertip/2484/import-data-from-microsoft-access-to-sql-server/
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How can I read a specific character from a text file?

    Hi All!
    I would like to read a specific character from a text file, e.g. the 2012th character in a text file with 7034 characters.
    How can I do this?
    Thanks
    Johannes

    just use the skip(long) method of the input stream that reads the text file and skip over the desired number of bytes

  • Filling an object ArrayList from a text file

    Hi all,
    I am developing a project (for university) which has a class named "SupplierAgent", which is required to keep database of custom objects of type "InventoryItem". Basically these consist of a String (for the name of the item), an int representing the quantity on hand, and an int representing the unit price (in cents). I wish to have this inventory loaded from a text file rather than a binary file - that way the user can add new items to the file before loading the agent.
    I have included the code below, which works provided the file is rigidly structured. The main problem is the user having to type the path to the file: I cannot guarantee the user will have the file in any folder, and so the user is required to type in the absolute path. Is there any way to make this less annoying? Or is there a better way of loading a preset inventory while allowing the user to edit that inventory at will?
    I have included the current code below. it's not exactly in accordance with coding standards, because we are using the JADE agent architecture (hence why the method is called "action") rather than something more informative.
    I should also mention that it uses a command line interface. The "io" class basically includes a scanner and the System.out.println method. Its "yesOrNo()" method is for convenience: it asks the user a question and allows them to select y or n.
    public void action() {
                boolean loadFromFile = io.yesOrNo("Would you like to load the inventory from a file?");
                if(loadFromFile) {
                    BufferedReader br = null;
                    boolean fileFound = false;
                    while(!fileFound) {
                        io.output("Please enter the absolute path to the file, including filename extension:  ");
                        inventoryFile = io.input();
                        try {
                            FileReader fr = new FileReader(inventoryFile);
                            br = new BufferedReader(fr);
                            fileFound = true;
                        catch (FileNotFoundException e) {
                            io.output("File not found.  ");
                    String fileLine = null;
                    int lineNumber = 1;
                    InventoryItem item = null;
                    try {
                        while((fileLine = br.readLine()) != null) {
                            switch((lineNumber % 4)) {
                            case 1: item = new InventoryItem();
                                    item.setName(fileLine); break;
                            case 2: item.setQuantity(Integer.parseInt(fileLine));
                            case 3: item.setPrice(Integer.parseInt(fileLine));
                            case 0: inventory.add(item);
                        io.output("Inventory loaded successfully\n");
                    catch(Exception e) {
                        io.output("Error at line " + lineNumber + " of inventory file\n");
                        io.output("Unable to fill inventory.  Please ensure file is structured correctly\n");
                        io.output("See readme for explanation of file structure requirements\n");
                        myAgent.doDelete();
            }Edited by: Swiftslide on Apr 22, 2010 6:34 PM

    You can use JFileChooser to allow the user to navigate to the required file.

  • How to insert data into Oracle db from MySQL db through PHP?

    Hi,
    I want to insert my MySQL data into Oracle database through PHP.
    I can access Mysql database using mysql_conect() & Oracle database using oci_connect() through PHP.
    Now How can I insert my data which is in MySQL into Oracle table. Both table structure are exactly same.
    So I can use
    insert into Oracle_Table(Oracle_columns....) values(Select * from MySQL_Table);
    But again problem is I can't open both connections at the same time.
    So has anyone done this before or anyone having any other idea..
    Plz guide me...

    You can do it if you setup a ODBC Gateway between MYSQL and Oracle DB. Then you can directly read from MySQL table using DB links and insert into Oracle table in one single SQL Statement.
    Otherwise you need to fetch the data from MySQL Into variables in your PHP Program and then insert into Oracle after binding the variables to the insert statement for Oracle. Hope that is clear enough.
    Regards
    Prakash

  • How to insert data into local database from oracle server

    I am new in C#.
    I am trying to design a local database in my C# project and I am trying to sync my database with our oracle server. I can login using oracle server. But I can't insert data into my local database from oracle server.
    anybody can help me ...............
    thanks..............................

    You can use SSIS package for that
    Start a new Integration Services project in Business  Intelligence Development Studio/ SSDT. Add a new SSIS package with a data flow task. Add a OLEDB source to connect to Oracle server and add a OLEDB Destination to connect to your local database.
    Select tables for source and destination. On executing package source data will get transferred to your local database.
    Please Mark This As Answer if it helps to solve the issue Visakh ---------------------------- http://visakhm.blogspot.com/ https://www.facebook.com/VmBlogs

  • How can i read all the lines from a text file in specific places and use the data ?

    string[] lines = File.ReadAllLines(@"c:\wmiclasses\wmiclasses1.txt");
    for (int i = 0; i < lines.Length; i++)
    if (lines[i].StartsWith("ComboBox"))
    And this is how the text file content look like:
    ComboBox Name cmbxOption
    Classes Win32_1394Controller
    Classes Win32_1394ControllerDevice
    ComboBox Name cmbxStorage
    Classes Win32_LogicalFileSecuritySetting
    Classes Win32_TapeDrive
    What i need to do is some things:
    1. Each time the line start with ComboBox then to get only the ComboBox name from the line for example cmbxOption.
       Since i have already this ComboBoxes in my form1 designer i need to identify where the cmbxOption start and end and when the next ComboBox start cmbxStorage.
    2. To get all the lines of the current ComboBox for example this lines belong to cmbxOption:
    Classes Win32_1394Controller
    Classes Win32_1394ControllerDevice
    3. To create from each line a Key and Value for example from the line:
    Classes Win32_1394Controller
    Then the key will be Win32_1394Controller and the value will be only 1394Controller
    Then the second line key Win32_1394ControllerDevice and value only 1394ControllerDevice
    4. To add to the correct belonging ComboBox only the value 1394Controller.
    5. To make that when i select in the ComboBox for example in cmbxOption the item 1394Controller it will act like i selected Win32_1394Controller.
    For example in this event:
    private void cmbxOption_SelectedIndexChanged(object sender, EventArgs e)
    InsertInfo(cmbxOption.SelectedItem.ToString(), ref lstDisplayHardware, chkHardware.Checked);
    In need that the SelectedItem will be Win32_1394Controller but the user will see in the cmbxOption only 1394Controller without the Win32_
    This is the start of the method InsertInfo
    private void InsertInfo(string Key, ref ListView lst, bool DontInsertNull)
    That's why i need that the Key will be Win32_1394Controller but i want that the user will see in the ComboBox only 1394Controller without the Win32_

    Hello,
    Here is a running start on getting specific lines in the case lines starting with ComboBox. I took your data and placed it into a text file named TextFile1.txt in the bin\debug folder. Code below was done in
    a console app.
    using System;
    using System.IO;
    using System.Linq;
    namespace ConsoleApplication1
    internal class Program
    private static void Main(string[] args)
    var result =
    from T in File.ReadAllLines(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "TextFile1.txt"))
    .Select((line, index) => new { Line = line, Index = index })
    .Where((s) => s.Line.StartsWith("ComboBox"))
    select T
    ).ToList();
    if (result.Count > 0)
    foreach (var item in result)
    Console.WriteLine("Line: {0} Data: {1}", item.Index, item.Line);
    Console.ReadLine();
    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my webpage under my profile but do not reply to forum questions.

  • Error while loading  data into External table from the flat files

    HI ,
    We have a data load in our project which feeds the oracle external tables with the data from the Flat Files(.bcp files) in unix.
    While loading the data, we are encountering the following error.
    Error occured (Error Code : -29913 and Error Message : ORA-29913: error in executing ODCIEXTTABLEOPEN callout
    ORA-29400: data cartridge error
    KUP-04063: un) while loading data into table_ext
    Please let us know what needs to be done in this case to solve this problem.
    Thanks,
    Kartheek

    Kartheek,
    I used Google (mine still works).... please check those links:
    http://oraclequirks.blogspot.com/2008/07/ora-29400-data-cartridge-error.html
    http://jonathanlewis.wordpress.com/2011/02/15/ora-29913/
    HTH,
    Thierry

Maybe you are looking for

  • Alert for AS2 Error on send

    Hi, We would like to setup some alerts for SAP outbound messages via AS2. When the Message is not able to be delivered to the customer we do get an "error on send" message in Seeburger Message Monitor. and the channel fails in the comm channel monito

  • POS inbound payment methods conversion

    Hi, In SAP retail customizing path, Sales Distribution, POS Interface, Adjustments, Conversions, I could define a conversion category and then for this converstion category I could creat conversion rules for payment methods. So I can map the payment

  • 10.5 crashes repeatedly - where do I start?

    Since upgrading to 10.5 iTunes crashes consistently shortly after launching (withng around 15 seconds).  This happens with no devices connected and Genius off. iTunes has encountered a problem and needs to close.  We are sorry for the inconvenience.

  • XL Reporter issue

    Hi Experts, When i run XL Reporter,i get the following Error message. "A required Com Addin program for XL Reporter has not been loaded and prohibits MS Excel from running". Pls help. Deepak

  • JAAS in WLS6

    Can anyone tell me the extent of support for JAAS in WLS 6, please, as I understand its not a full implementation. We're interested in using JAAS with WL6 to provide a single logon to the system so that when a user tries to access other services duri