Question

I am trying to read a CSV file in to my application to read a bunch of data into a table. Every row is separated by commas and each end of the row has a carriage return. I try using the scanner in java to read the first line with delimiter set to (","), but I can't figure out how to stop the scanner at the end of the first row when it reached the carriage return. This is the code I have so far that scans in everything in the file since it doesn't stop at carriage returns.

Scanner scn = new Scanner(inputStream);

                    Vector<String> columnTitles = new Vector<String>();
                    scn.useDelimiter(",");

                    // Read the first line to get the column names.
                    while(!scn.hasNextInt())
                    {
                        String newStr = scn.next();
                        columnTitles.add(newStr);
                        System.out.print(newStr);
                    }

The idea seems so simple, yet everywhere I look has useless examples that all don't work.

Was it helpful?

Solution

If you're simply trying to populate the columnTitles vector with the first line of the file and then process the rest of the file (or not)

  1. Use a BufferedReader on your file to read the first line into a string
  2. Create a scanner using that string
  3. Populate the vector using the scanner from step 2
  4. Then if you want to process the rest of the file, do what you are doing above but call scn.nextLine() before your while loop to skip the first line of the file

OTHER TIPS

You could use two scanners:

new Scanner(scanner.nextLine());

or a BufferedReader and a scanner

new Scanner(bufferedReader.readLine());

or BufferedReader and split.

bufferedReader.readLine().split(",");

In your case I think the only thing you gain from scanner is the ability to call nextInt() instead of converting the String to an int yourself (which is easy enough to do).

A Carriage Return is a control character in Unicode/ASCII, and can be identified by its hex value just like any other "visible" character. New Line is 0x0A (10), and Carriage Return (they are slightly different things) is 0x0D (13).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top