0

I want to read a CSV file in java and store this data in an array to be able to search using this data in another function.

public ArrayList < Resp > processTextToRespList(String filePath) throws IOException {
    ArrayList < data > result = new ArrayList < data > ();
    br = new BufferedReader(new FileReader(csvFile));
    while((row = BufferedReader.readNext()) != null) {
        String line = scan.nextLine();
        String[][]  lineArray = line.split(" ");
        result.add(new esp(lineArray[0], lineArray[1], lineArray[2]));
    }
    return result;
}
Ahmed Ashour
  • 4,209
  • 10
  • 29
  • 46
step
  • 1
  • what is your search criteria? – Atul Mar 09 '17 at 18:56
  • its an ldap search. but im ok with at bit i just cant get my head arounf reading the file and storing the information so i can do the seach on each line. – step Mar 09 '17 at 19:06
  • If it's a key-value pair kind of file then use Map instead of ArrayList because retrieval will be much faster in case of search. – Atul Mar 09 '17 at 19:10
  • Possible duplicate of [Java - Read CSV with Scanner()](http://stackoverflow.com/questions/14274259/java-read-csv-with-scanner) – Matt Goodrich Mar 09 '17 at 19:15

1 Answers1

0

I don't really understand what is your issue, but I guess it has to do with the code you've given. I fixed the obvious mistakes to turn it into something more compilable :

public List < Resp > processTextToRespList(String filePath) throws IOException {
    List<Resp> result = new ArrayList<>();
    File csvFile = new File(filePath);
    try(BufferedReader br = new BufferedReader(new FileReader(csvFile))){
        String row;
        while((row = br.readLine()) != null) {
            String[] lineArray = row.split(" ");
            result.add(new Resp(lineArray[0], lineArray[1], lineArray[2]));
        }
    }
    return result;
}

I haven't corrected any logic, I just used the variables you declared instead of the initial non-java code you've written and closed the FileReader. Tell me if that is enough for you or if your issue is more complex than that.

Explanation :

I've declared the result as a List instead of an ArrayList because it's my own sensibility talking, no real error here.

You've created a FileReader over a csvFile but never declared any csvFile, I assumed it was the File generated from your filePath.

I declared the FileReader and BufferedReader in a try-with-resources block so that they'll be closed automatically.

I called readLine on br because it's the BufferedReader we instantiated, you can't just call a static method (which does not exist) and hope it'll work.

I split the row we just read, and not some line read from a scanner which was never declared.

All in all, I just fixed some obvious errors that probably appeared while copy-pasting some code without any thought. I'm not sure if you did understand what you were writting nor what you were doing.

Jeremy Grand
  • 2,061
  • 9
  • 18