我用Java编写了一个csvReader方法。 一切似乎都可以正常工作,但是在打印值时只是跳过了第一列中每一行的第一个字母。这是我的代码=>
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();
}
}
这里“学生”只是一个具有firstName,lastName,id和age字段的POJO类。在获取输出为=>
Student details : ID = 101 first name = ikhil Last name = Chaurasia age = 28
Student details : ID = 102 first name = adhna Last name = Chaurasia age = 28
结果应为=>
Student details : ID = 101 first name = Nikhil Last name = Chaurasia age = 28
Student details : ID = 102 first name = Sadhna Last name = Chaurasia age = 28
csv文件内容如下所示:
toString方法的实现如下所示:
public String toString() {
return "Student details : ID = "+id+ " first name = "+firstName+ " Last name = "+lastName+ " age = "+age;
}
任何帮助将不胜感激。 谢谢
答案 0 :(得分:2)
问题出在您的while
循环条件中:fileReader.read() > 0
。
每次调用该字符时都会读取一个字符(例如“ N”,“ S”),这将导致随后对readLine
的调用会跳过第一个字符。
相反,只需使用readLine
检查条件即可:
String line;
while ((line = fileReader.readLine()) != null) {
String[] tokens = line.split(COMMA_DELIMETER);
// do the rest of the stuff
}