Md. Mohibur Rahman
Md. Mohibur Rahman

Reputation: 45

How to read two or more word separeted by comma in a line in a CSV file in Java?

Here is my CSV file:

11608030,12345  
11608045,54321  

Here is my code:

package csvtest;
import java.util.ArrayList;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class Test {
    private ArrayList<Long> account_number = new ArrayList<Long>();
    private ArrayList<String> password = new ArrayList<String>();
    public Test() throws FileNotFoundException {
        Scanner scanner = new Scanner(new File("E:\\account.csv"));

        scanner.useDelimiter(",");
        while(scanner.hasNext()){
            this.account_number.add(Long.parseLong(scanner.next()));
            this.password.add(scanner.next());
        }
        System.out.println(account_number);
    }
}

and in the main class there is only one command

Test test = new Test();

but when i run this code i got a message like this

Exception in thread "main" java.util.NoSuchElementException at java.util.Scanner.throwFor(Scanner.java:862) at java.util.Scanner.next(Scanner.java:1371) at csvtest.Test.(Test.java:28) at csvtest.CSVTest.main(CSVTest.java:21) C:\Users\hp\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1 BUILD FAILED (total time: 0 seconds)

whats wrong with my code?? need help!!! thanks in advance :)

Upvotes: 0

Views: 109

Answers (2)

Alan Blyth
Alan Blyth

Reputation: 195

scanner.next() gets you a line from the file, you then need to split that line into your comma seperated values:

See example:

    @Test 
    void parseAccountsCsvFile() throws FileNotFoundException {
        
        ArrayList<Long> account_number = new ArrayList<Long>();
        ArrayList<String> password = new ArrayList<String>();
           Scanner scanner = new Scanner(new File("accountsCsvTest.txt"));
   
           while(scanner.hasNext()){
            String scannerLine = scanner.next();
            String[] values = scannerLine.split(",");
               account_number.add(Long.valueOf(values[0]));
               password.add(values[1]);
           }
           System.out.println(account_number);
           System.out.println(password);
           scanner.close();
       }
   }

Output:

[11608030, 11608045]

[12345, 54321]

I think that is what you are looking for.

Upvotes: 1

dannygme
dannygme

Reputation: 81

You should use scanner.useDelimiter(",|\\n"); The issue that you originally had was that the second scanner.next() read in "12345\n11608045" since you didn't specify that a newline could be a delimiter as well. So when scanner.next() was called the last time there wasn't anything to read from since that second call to next() read two of your values.

Upvotes: 4

Related Questions