我使用了两个文件读取类,scanner 和 bufferedReader。在阅读代码时,您必须避免其中之一的部分。我把它们写在一起只是为了便于理解。现在的问题是为什么我在使用缓冲阅读器而不是此代码的扫描仪类时遇到错误。扫描仪适用于此代码。我在 parseRecord 方法中收到异常错误。在这段代码中,我试图解析一个 csv,我有几个类正在使用它的输出,但我被困在这里,想知道为什么 bufferedReader 的工作方式与扫描仪不同。
public List<? extends ReportRecord> load() throws Exception {
List<SportPopularityReportRecord> records=new ArrayList<SportPopularityReportRecord>();
// first way using buffered reader, please ignore the scanner part below.
BufferedReader br;
try {
br= new BufferedReader(new FileReader(filePath.toString()));
String line=br.readLine();
if ((line = br.readLine()) != null)
{
parseHeader(line);
}
while(line != null)
{
line= br.readLine();
records.add(parseRecord(line));
}
}
catch (FileNotFoundException ex)
{
ex.printStackTrace();
}
catch (IOException ex)
{
ex.printStackTrace();
}
finally
{
br.close();
// fis.close();
}
}
// Second way using scanner class, please ignore the buffered reader part above.
String s;
Scanner sc=new Scanner(filePath.toFile());
//getting header
if(sc.hasNextLine()){
s=sc.nextLine();
parseHeader(s);
}
//getting recored
while(sc.hasNextLine()){
s=sc.nextLine();
records.add(parseRecord(s));
}
//sort the record
Collections.sort(records, new SportPopularityReportRecordComparator());
recordList=records;
//return record List
return recordList;
}
public SportPopularityReportRecord parseRecord(String strRecord) {
String [] s=strRecord.split(",");
SportPopularityReportRecord r=new SportPopularityReportRecord();
r.setSport(s[0]);
r.setRank(Integer.parseInt(s[1]));
return r;
}