Page 1 of 2 12 LastLast
Results 1 to 20 of 22
  1. #1
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default read a csv file in an array list

    Hi,
    I am using this piece of code (below) to read an excel file into an array list. How can I change it to make it read a csv file? Note: it should, when done, return the same array list.

    Any help would be greatly appreciated. Thanks


    public static ArrayList<ImportedSimulationRecord> readSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation)
    {
    File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);

    ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();

    try
    {
    if (mySimParamToAnalyze.exists())
    {
    Workbook wb = Workbook.getWorkbook(mySimParamToAnalyze);
    Sheet sheet = wb.getSheet(0);

    for(int i = 1; i < sheet.getRows(); i++)
    {
    Cell[] cells = sheet.getRow(i);
    ArrayList<String> fields = new ArrayList<String>();

    for(Cell cell: cells) {
    fields.add(cell.getContents());
    }
    records.add(new ImportedSimulationRecord(fields));
    }
    }
    } catch (Throwable t) {
    t.printStackTrace();
    }
    return records;
    }

  2. #2
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    What import statements do you need to compile your code?
    Since a csv file is text, you could read the file line by line and use the String split method to populate an array that could be used to build the fields arraylist.

    Please use code tags when posting code. See: BB Code List - Java Forums

  3. #3
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default

    Norm,
    thanks for your answer. Sorry though: what do you mean by import statement? Also, I have looked around for code samples and they all point to what you are saying. The problem is that I cannot make it work. I tried using a BufferedReader, but when I type:
    BufferedReader bufRdr = new BufferedReader(new FileReader(mySimParamToAnalyze));
    it keeps telling me that it cannot find the BufferedReader construtor.

    Also, how would you go about telling the program to take each element in a line (for example, let's imagine the line is 1, 3, 450, 456, hello, nice, 123) and put it into:
    Cell[] cells?

    Again, I really appreciate your help on this.
    Patrick

  4. #4
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    it keeps telling me that
    When you get errors, copy and paste here the full text of the error message. Without that we can't know what is wrong.
    to take each element in a line
    Did you look at the String class's split method?

  5. #5
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default

    Norm,
    thanks for your reply. That is the error message I receive. (note: java.io.*; is imported)

    Error message:
    cannot find symbol
    symbol: constructor BufferedReader(model.readers.FileReader)
    location; class java,io,BufferedReader

    I'll look deeper into the string class's split method

  6. #6
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    what do you mean by import statement?
    Then you say: (note: java.io.*; is imported)
    I'm confused by your question.
    constructor BufferedReader(model.readers.FileReader)
    Look at the API doc for the BufferedReader class and for the model.readers.FileReader class.
    The compiler doesn't think that the BufferedReader has a constructor that takes a model.readers.FileReader for an argument.

  7. #7
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default

    Norm,
    sorry, my bet on the error. The class I was working with was also called FileReader, and I suppose the compiler thought I was trying to give the BuffereReader constructor my class as an argument. Anyway, I changed the name of the class and it works now.

    Still do not know how to use the String split method though.

  8. #8
    Norm's Avatar
    Norm is offline Moderator
    Join Date
    Jun 2008
    Location
    SW Missouri
    Posts
    17,457
    Rep Power
    25

    Default

    Did you read the API doc?
    The regex can be simplified to a single character: "," for a csv.

    Do a search on the forum for coding examples.

    Or from the top of my head:
    String aCSV = "a,b,c,d";
    String[] fields = aCSV.split(",");
    System.out.println("fields=" + java.util.Arrays.toString(fields)); // show contents of the array

  9. #9
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default

    Norm,
    thanks a lot for your help. The little example you gave me helped me a lot, and now my code works and I also made it to skip the header.

    I still have some trouble understanding the try-catch statements and the exception handling, but that is another story.

    Again, thank a lot for your help!
    How can I close the thread, or mark it solved?

  10. #10
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Quote Originally Posted by dellacpa View Post
    Norm,
    thanks a lot for your help. The little example you gave me helped me a lot, and now my code works and I also made it to skip the header.

    I still have some trouble understanding the try-catch statements and the exception handling, but that is another story.

    Again, thank a lot for your help!
    How can I close the thread, or mark it solved?
    If it's not too much, could you post your final code please? This is interesting. The full thing please between the right tags "
    Java Code:
    YOURCODEHERE
    "

    THANKS.

  11. #11
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default

    Sure,
    here below is the code (hope to have put it between the right tags)

    Java Code:
     
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
        {
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
    
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
    
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
            
            String line = null;
    
            int row = 0;
            
            while ((line = bufRdr.readLine()) != null)
            {
                if (row == 0)
                {
    
                }
                else
                {
                    String[] strings = line.split(",");
                    ArrayList<String> fields = new ArrayList<String>();
    
                    for (String string: strings)
                    {
                        fields.add(string);
                    }
    
                    records.add(new ImportedSimulationRecord(fields));
                }
    
                row++;
            }        
            bufRdr.close();
            
            return records;
        }

  12. #12
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Thank you dellacpa. I am new to Java so I'm learning to decipher codes to better understand how they work and how to write my own codes.

    and yes, you used the right tags. Thanks. I'm guessing you left out the class declaration and the main method on purpose?

    Actually, I just tried to add a main method and class declaration around it:

    Java Code:
    public class Readcsvintoarray {
    	public static void main(String[] args) {
    	
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
        {
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
    
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
    
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
            
            String line = null;
    
            int row = 0;
            
            while ((line = bufRdr.readLine()) != null)
            {
                if (row == 0)
                {
    
                }
                else
                {
                    String[] strings = line.split(",");
                    ArrayList<String> fields = new ArrayList<String>();
    
                    for (String string: strings)
                    {
                        fields.add(string);
                    }
    
                    records.add(new ImportedSimulationRecord(fields));
                }
    
                row++;
            }        
            bufRdr.close();
            
            return records;
       }
    }
    and if my classes are properly "closed" meaning my the number of opening { matches the number of closing }, it allows me to click save and it automatically pulls the same of the file from the class declaration. In this case, it's not working. Do you have the full code.

    This is what I get when I try to generate a CSD:

    Java Code:
    [Grasp 6]:4:78:4:78: parse error at or before "("
    ... ublic static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throw
    ...

  13. #13
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Java Code:
    if (row == 0) {
    
    } else {
    ARRRRRRRRRRRGGGGGGGGGGGGH!

    Make the bad code go away.

    Java Code:
    if(row!= 0) {
        // do stuff
    }
    Uising an empty if statement to get around the logic is just awful!

  14. #14
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    Quote Originally Posted by bigsonny View Post
    it's not working.
    You have placed the readCSVSimParamToBeAnalyzed method inside the main method. Thats a no-no!

  15. #15
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Thanks. I deleted my main method and used this code, which allowed me to save it, but then I ended up with the following:

    The code:
    Java Code:
    public class Readcsvintoarray {
    	
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
        {
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
    
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
    
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
            
            String line = null;
    
            int row = 0;
            
            while ((line = bufRdr.readLine()) != null)
            {
                if (row == 0)
                {
    
                }
                else
                {
                    String[] strings = line.split(",");
                    ArrayList<String> fields = new ArrayList<String>();
    
                    for (String string: strings)
                    {
                        fields.add(string);
                    }
    
                    records.add(new ImportedSimulationRecord(fields));
                }
    
                row++;
            }        
            bufRdr.close();
            
            return records;
       }
    }
    The error:

    Java Code:
     ----jGRASP exec: javac -g Readcsvintoarray.java
    
    Readcsvintoarray.java:3: cannot find symbol
    symbol  : class ArrayList
    location: class Readcsvintoarray
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
                  ^
    Readcsvintoarray.java:3: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
                            ^
    Readcsvintoarray.java:3: cannot find symbol
    symbol  : class FileNotFoundException
    location: class Readcsvintoarray
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
                                                                                                                               ^
    Readcsvintoarray.java:3: cannot find symbol
    symbol  : class IOException
    location: class Readcsvintoarray
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
                                                                                                                                                      ^
    Readcsvintoarray.java:5: cannot find symbol
    symbol  : class File
    location: class Readcsvintoarray
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
            ^
    Readcsvintoarray.java:5: cannot find symbol
    symbol  : class File
    location: class Readcsvintoarray
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
                                           ^
    Readcsvintoarray.java:7: cannot find symbol
    symbol  : class ArrayList
    location: class Readcsvintoarray
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
            ^
    Readcsvintoarray.java:7: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
                      ^
    Readcsvintoarray.java:7: cannot find symbol
    symbol  : class ArrayList
    location: class Readcsvintoarray
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
                                                              ^
    Readcsvintoarray.java:7: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
                                                                        ^
    Readcsvintoarray.java:9: cannot find symbol
    symbol  : class BufferedReader
    location: class Readcsvintoarray
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
            ^
    Readcsvintoarray.java:9: cannot find symbol
    symbol  : class BufferedReader
    location: class Readcsvintoarray
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
                                         ^
    Readcsvintoarray.java:9: cannot find symbol
    symbol  : class FileReader
    location: class Readcsvintoarray
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
                                                            ^
    Readcsvintoarray.java:24: cannot find symbol
    symbol  : class ArrayList
    location: class Readcsvintoarray
                    ArrayList<String> fields = new ArrayList<String>();
                    ^
    Readcsvintoarray.java:24: cannot find symbol
    symbol  : class ArrayList
    location: class Readcsvintoarray
                    ArrayList<String> fields = new ArrayList<String>();
                                                   ^
    Readcsvintoarray.java:31: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
                    records.add(new ImportedSimulationRecord(fields));
                                    ^
    16 errors
    
     ----jGRASP wedge2: exit code for process is 1.
     ----jGRASP: operation complete.
    Please don't give me the solution, just some directions...please.

    so I added an import statement, leading to the following code:

    Java Code:
    import java.util.ArrayList;
    
    public class Readcsvintoarray {
    	
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
        {
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
    
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
    
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
            
            String line = null;
    
            int row = 0;
            
            while ((line = bufRdr.readLine()) != null)
            {
                if (row == 0)
                {
    
                }
                else
                {
                    String[] strings = line.split(",");
                    ArrayList<String> fields = new ArrayList<String>();
    
                    for (String string: strings)
                    {
                        fields.add(string);
                    }
    
                    records.add(new ImportedSimulationRecord(fields));
                }
    
                row++;
            }        
            bufRdr.close();
            
            return records;
       }
    }
    and brought my errors down to 11 :mixed feelings:

    Java Code:
     ----jGRASP exec: javac -g Readcsvintoarray.java
    
    Readcsvintoarray.java:5: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
                            ^
    Readcsvintoarray.java:5: cannot find symbol
    symbol  : class FileNotFoundException
    location: class Readcsvintoarray
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
                                                                                                                               ^
    Readcsvintoarray.java:5: cannot find symbol
    symbol  : class IOException
    location: class Readcsvintoarray
    public static ArrayList<ImportedSimulationRecord> readCSVSimParamToBeAnalyzed(String simParamToAnalyzeFileLocation) throws FileNotFoundException, IOException
                                                                                                                                                      ^
    Readcsvintoarray.java:7: cannot find symbol
    symbol  : class File
    location: class Readcsvintoarray
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
            ^
    Readcsvintoarray.java:7: cannot find symbol
    symbol  : class File
    location: class Readcsvintoarray
            File mySimParamToAnalyze = new File(simParamToAnalyzeFileLocation);
                                           ^
    Readcsvintoarray.java:9: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
                      ^
    Readcsvintoarray.java:9: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
            ArrayList<ImportedSimulationRecord> records = new ArrayList<ImportedSimulationRecord>();
                                                                        ^
    Readcsvintoarray.java:11: cannot find symbol
    symbol  : class BufferedReader
    location: class Readcsvintoarray
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
            ^
    Readcsvintoarray.java:11: cannot find symbol
    symbol  : class BufferedReader
    location: class Readcsvintoarray
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
                                         ^
    Readcsvintoarray.java:11: cannot find symbol
    symbol  : class FileReader
    location: class Readcsvintoarray
            BufferedReader bufRdr  = new BufferedReader(new FileReader(mySimParamToAnalyze));
                                                            ^
    Readcsvintoarray.java:33: cannot find symbol
    symbol  : class ImportedSimulationRecord
    location: class Readcsvintoarray
                    records.add(new ImportedSimulationRecord(fields));
                                    ^
    11 errors
    
     ----jGRASP wedge2: exit code for process is 1.
     ----jGRASP: operation complete.

  16. #16
    Junky's Avatar
    Junky is offline Grand Poobah
    Join Date
    Jan 2011
    Location
    Dystopia
    Posts
    3,798
    Rep Power
    7

    Default

    You have to import all the classes. However I suspect ImportedSimulationRecord is a custom class of the OP. You could try writing it yourself or think about how you could modify the code so it doesn't use that class.

  17. #17
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Okay thanks!

  18. #18
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default

    To Junky:
    thanks for your advice on the if statement. However, I believe that if something does the tric it does not really matter if you find it awful or not.
    To Bigsonny:
    Yes, ImportedSimulationRecord is another class I have created for my model. The goal of my model was to use the data contained in the .csv file to create objects (the importedSimulationRecord). here below is an example of the ImportedSimulationRecord class
    Java Code:
    public static final int COL_FIRST_COLUMN_IN_CSV_FILE           = 0;
    public static final int COL_SECOND_COLUMN_IN_CSV_FILE        = 1;
    public static final int COL_THIRD_COLUMN_IN_CSV_FILE           = 2;
    
    private int dataFromFirstColumn;
    private int dataFromSecondColumn;
    private int dataFromThirdColumn;
    
    public ImportedSimulationRecord(ArrayList<String> fields)
        {
            dataFromFirstColumn = Integer.valueOf(fields.get(COL_FIRST_COLUMN_IN_CSV_FILE));
    dataFromSecondColumn = Integer.valueOf(fields.get(COL_SECOND_COLUMN_IN_CSV_FILE));
    dataFromThirdColumn = Integer.valueOf(fields.get(COL_THIRD_COLUMN_IN_CSV_FILE));
    
    
    }

  19. #19
    bigsonny is offline Senior Member
    Join Date
    Nov 2010
    Posts
    164
    Rep Power
    4

    Default

    Quote Originally Posted by dellacpa View Post
    To Junky:
    thanks for your advice on the if statement. However, I believe that if something does the tric it does not really matter if you find it awful or not.
    To Bigsonny:
    Yes, ImportedSimulationRecord is another class I have created for my model. The goal of my model was to use the data contained in the .csv file to create objects (the importedSimulationRecord). here below is an example of the ImportedSimulationRecord class
    Java Code:
    public static final int COL_FIRST_COLUMN_IN_CSV_FILE           = 0;
    public static final int COL_SECOND_COLUMN_IN_CSV_FILE        = 1;
    public static final int COL_THIRD_COLUMN_IN_CSV_FILE           = 2;
    
    private int dataFromFirstColumn;
    private int dataFromSecondColumn;
    private int dataFromThirdColumn;
    
    
    
    public ImportedSimulationRecord(ArrayList<String> fields)
        {
            dataFromFirstColumn = Integer.valueOf(fields.get(COL_FIRST_COLUMN_IN_CSV_FILE));
    dataFromSecondColumn = Integer.valueOf(fields.get(COL_SECOND_COLUMN_IN_CSV_FILE));
    dataFromThirdColumn = Integer.valueOf(fields.get(COL_THIRD_COLUMN_IN_CSV_FILE));
    
    
    }
    Thanks dellaCPA. Do you have the full class though with the actual class declaration? I know this sounds trivial but I ended up putting the other method in the wrong place and had a bunch of errors with the main class of your code? If you want to replace the name of your class with a bunch of XXXXs that's fine, but I just need to know that there are no import statements that I am not seeing or something else. Thanks.

  20. #20
    dellacpa is offline Member
    Join Date
    Aug 2010
    Posts
    16
    Rep Power
    0

    Default

    Bigsonny:
    to use the code I wrote you need three separated classes: 1) Main, 2) FileReaderClass, 3) ImportedSimulationRecord.
    (besides the Main class, you can call the other classes whatever you want)

    In the Main class (I put that in the run() method), you call the method
    Java Code:
    ArrayList<ImportedSimulationRecord> importedSimulationRecords =
                    FileReaderClass.readCSVSimParamToBeAnalyzed
                    (location of the file in the form of "C:/Desktop/parameters.csv");
    this simply tells the FileReaderClass to read the .cvs file and to create the ArrayList<ImportedSimulationRecord> importedSimulationRecords.

    Now you have an ArrayList with the informations from the csv file ready to be used. Hope this helps.

Page 1 of 2 12 LastLast

Similar Threads

  1. need to read information from file into array
    By sadeem in forum New To Java
    Replies: 8
    Last Post: 05-15-2011, 10:00 PM
  2. read input file into array
    By randoms:) in forum New To Java
    Replies: 3
    Last Post: 04-23-2011, 08:52 AM
  3. Replies: 2
    Last Post: 04-20-2011, 05:39 PM
  4. Help needed: read array from file and then use it
    By ChicagoAve in forum New To Java
    Replies: 11
    Last Post: 02-18-2011, 01:02 PM
  5. Read File into 2d array
    By almjodla in forum New To Java
    Replies: 8
    Last Post: 03-23-2010, 02:55 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •