[英]How to recognize carriage return using java scanner
I am trying to read a CSV file in to my application to read a bunch of data into a table. 我正在尝试将CSV文件读取到我的应用程序中,以将一堆数据读取到表中。 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. 我尝试在Java中使用扫描仪读取定界符设置为(“,”)的第一行,但是当它到达回车符时,我无法弄清楚如何在第一行末尾停止扫描仪。 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. 这个想法似乎很简单,但是我到处都看不到没有用的例子,所有例子都不起作用。
You could use two scanners: 您可以使用两个扫描仪:
new Scanner(scanner.nextLine());
or a BufferedReader and a scanner 或BufferedReader和扫描仪
new Scanner(bufferedReader.readLine());
or BufferedReader and split. 或BufferedReader并拆分。
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). 在您的情况下,我认为您从扫描程序中获得的唯一好处是能够调用nextInt()而不是自己将String转换为int(这很容易做到)。
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) 如果您只是尝试用文件的第一行填充columnTitles向量,然后处理文件的其余部分(或不处理)
A Carriage Return is a control character in Unicode/ASCII, and can be identified by its hex value just like any other "visible" character. 回车符是Unicode / ASCII格式的控制字符,可以像其他任何“可见”字符一样由其十六进制值来标识。 New Line is 0x0A (10), and Carriage Return (they are slightly different things) is 0x0D (13). 换行是0x0A(10),回车符(它们稍有不同)是0x0D(13)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.