简体   繁体   中英

Creating Strings while Reading a CSV ( Java)

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.

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);

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM