我已經使用了兩個文件讀取類,scanner和bufferedReader。在閱讀代碼時,你必須避免其中的一部分。爲了便於理解,我將它們寫在一起。現在問題是爲什麼我在使用緩衝閱讀器而不是掃描儀類代碼時出現錯誤。掃描儀可以正常使用此代碼。我在parseRecord方法中遇到異常錯誤。在這段代碼中,我試圖解析一個csv,我有幾個類正在使用它的輸出,但我卡在這裏,想知道爲什麼bufferedReader不像掃描器一樣工作。爲什麼Bufferereader和掃描儀的輸出不同?
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;
}
什麼樣的錯誤?輸出差異是什麼?請更具體。 – Antoniossss