How to recognize carriage return using java scanner

南楼画角 提交于 2019-12-13 21:03:55

问题


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.


回答1:


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



回答2:


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




回答3:


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



来源:https://stackoverflow.com/questions/18859224/how-to-recognize-carriage-return-using-java-scanner

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!