0

私は 2 つのファイル読み取りクラス、scanner と bufferedReader を使用しました。コードを読んでいる間、それらのいずれかの部分を避ける必要があります。分かりやすいようにまとめて書いてみました。ここで問題は、このコードのスキャナー クラスの代わりにバッファー リーダーを使用しているときにエラーが発生する理由です。Scanner はこのコードで正常に動作します。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;
            }
4

1 に答える 1

1

これを試してみてください。

String line=br.readLine();
if (line != null) 
{
    parseHeader(line);
}

あなたは物事を2回読んでいます。

于 2013-11-05T06:55:05.973 に答える