[英]csvReader is skipping the first alphabet of every row of fist column while reading from a csv file
I wrote a csvReader method in Java. 我用Java编写了一个csvReader方法。 Everything seems to work fine, but it is just skipping the very first alphabet of every row in first column while printing the values.
一切似乎都可以正常工作,但是在打印值时只是跳过了第一列中每一行的第一个字母。 Here is my code =>
这是我的代码=>
public static void csvReader(String fileName) {
try {
BufferedReader fileReader = new BufferedReader(new FileReader(fileName));
List<Student> students = new ArrayList<>();
fileReader.readLine();
while (fileReader.read() > 0) {
String line = fileReader.readLine();
String[] tokens = line.split(COMMA_DELIMETER);
if (tokens.length > 0) {
Student student = new Student(tokens[0], tokens[1], Integer.valueOf(tokens[2]),
Integer.valueOf(tokens[3]));
students.add(student);
}
}
students.forEach(System.out::println);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Here "Student" is just a POJO class having firstName, lastName, id and age fields. 在这里,“学生”只是一个具有firstName,lastName,id和age字段的POJO类。 In am getting the output as =>
在我得到的输出为=>
Student details : ID = 101 first name = ikhil Last name = Chaurasia age = 28
Student details : ID = 102 first name = adhna Last name = Chaurasia age = 28
Where the result should be like => 结果应该像=>
Student details : ID = 101 first name = Nikhil Last name = Chaurasia age = 28
Student details : ID = 102 first name = Sadhna Last name = Chaurasia age = 28
The csv file content are shown below : csv文件的内容如下所示:
The toString method is implemented as shown below : toString方法的实现如下所示:
public String toString() {
return "Student details : ID = "+id+ " first name = "+firstName+ " Last name = "+lastName+ " age = "+age;
}
Any help would be highly appreciated. 任何帮助将不胜感激。 Thanks
谢谢
The issue is in your while
loop condition: fileReader.read() > 0
. 问题出在您的
while
循环条件中: fileReader.read() > 0
。
This reads a single character every time you call it (such as 'N', 'S'), which causes the subsequent call to readLine
to skip the first character. 每次调用该字符时都会读取一个字符(例如“ N”,“ S”),这将导致随后对
readLine
调用会跳过第一个字符。
Instead, just check the condition using readLine
: 相反,只需使用
readLine
检查条件:
String line;
while ((line = fileReader.readLine()) != null) {
String[] tokens = line.split(COMMA_DELIMETER);
// do the rest of the stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.