0

I'am Scanning a CSV File with the following Code:

public void scanFile() {
    boolean isNumber = false;
    String test;

    try {
        sc = new Scanner(Gui.selectedFile);
        sc.useDelimiter("[;\"]");


        while (sc.hasNext() && isNumber == false) {

            test = sc.next();
                if(test.equals("{9}")) {
                    System.out.println("success");
                }


            System.out.println();;
            if (sc.hasNextInt()) {
                isNumber = true;
            }
        } sc.close();

    } catch (Exception e) {
        System.out.println("error");
    }

Now i need a way, to create a String for EACH entry in the CSV. There are around 60 entry's in my CSV. I need to use the read data further in the program.

1
  • 1
    Why not put them into an array of strings? Commented Mar 20, 2018 at 15:14

2 Answers 2

1

You can do it the following way with just 3 lines of code:

List<List<String>> data = new ArrayList<List<String>>();
List<String> lines = Files.lines(Paths.get(file)).collect(Collectors.toList());
lines.stream().forEach(s -> data.add(Arrays.asList(s.split(","))));

Here's what it does. The second line above reads all the lines from the CSV file. In the third line, we stream through all the lines (one line at a time) and split the line with a comma as a separator. This split gives us an array of cells in that line. We just convert the array to a list and add it to our datastructure data which is a list of lists.

Later, say, if you want to access the value of 7th cell in the 4th row of the CSV, all you have to do is following:

String cell = data.get(3).get(6);

Sign up to request clarification or add additional context in comments.

2 Comments

Can you explain me what you did? Thank you!
@ErwinIvanov, I put some explanation. See if it helps.
0
public ArrayList<String> scanFile() {
boolean isNumber = false;
String test;
ArrayList<String> output = new ArrayList<String>();

try {
    sc = new Scanner(Gui.selectedFile);
    sc.useDelimiter("[;\"]");


    while (sc.hasNext() && isNumber == false) {

        test = sc.next();
             output.add( test );

            if(test.equals("{9}")) {
                System.out.println("success");
            }


        System.out.println();;
        if (sc.hasNextInt()) {
            isNumber = true;
        }
    } sc.close();

} catch (Exception e) {
    System.out.println("error");
}

return output;
}

2 Comments

How can i access a entry in the arrayList ?
Use the get() method of the arraylist. get( 5) will return the fifth element of the ArrayList.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.