簡體   English   中英

如何查找 BufferedReader 文件中是否存在一行?

[英]How to find if a line exists in the BufferedReader file?

我在 Java 中有這個方法,它在另一個方法的 try 塊中調用。 importFormat 在 try 塊中返回具有分配值的 class(//做需要的事情)。 該方法應該逐行讀取文件。 如果對帶有 try 塊的方法的方法調用被調用的次數多於文件中的行數,importFormat() 應該返回 null。

我試圖用 if 塊檢查它,雖然它做的不多並且總是返回 ClassName。 似乎 class 總是存儲文件的第一行。

private ClassName importFormat(BufferedReader br) throws IOException, ParseException {

String out;
Track t = new ClassName();

if((out = br.readLine()) == null) return null;

    //do what is needed

    }else{
        t = null; //here I unsuccessfully tried to force the method to again return null, no luck
        System.err.print(out);
        throw new ParseException("", 0);
    }

return t;

}

我也嘗試過 br.ready() 方法,它沒有任何區別

編輯:我注意到我錯誤地復制了代碼,對此我很抱歉。 這里應該更清楚最小可重現代碼:

private ClassName foo(BufferedReader br) throws IOException {
    ClassName t = new ClassName();
    String out = null;

    out = br.readLine();
    if(out.equals(null)) return null; //handle the case where there's no more line to read

    if(/*!string red from BufferedReader.isEmpty()*/){
        //do something
    }else{
        t = null; //ensure that null would be returned
        //do something more unrelated to this question
    }
    return t;
}

我不太明白你的問題,但我認為你不應該這樣比較:

if((out = br.readLine()) == null) return null;

要比較 java 中的字符串,請改用 str1.equals(str2)。 所以我認為你應該嘗試:

if(out.equals(br.readLine())) {
    //do sth here because "out" exists in BufferReader.
} else {
    System.out.println("Continue searching...\n");
}

return t;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM