簡體   English   中英

Java BufferedReader.readLine()在讀取文件時返回null

[英]Java BufferedReader.readLine() returning null when reading file

我需要協助。 這是我的功能:

public String[] getLines(String filename) {
    String[] returnVal = null;
    int i = 0;

    try {
        BufferedReader br = new BufferedReader(new FileReader(new File(filename)));

        for(String line; (line = br.readLine()) != null; ) {
            // process the line.
            returnVal[i] = line;
            i++;
        }

        br.close();
    }
    // Catches any error conditions
    catch (Exception e)
    {
        debug.error("Unable to read file '"+filename+"'");
        debug.message(e.toString());
    }

    return returnVal;
}

這應該返回我String []數組以及來自指定文件的所有行。 但是我只得到異常作為回報:

java.lang.NullPointerException

當我嘗試打印結果時,它為null。 有任何想法嗎? 謝謝!

您正在將值顯式設置為null

String[] returnVal = null;

由於您不知道它將包含多少個元素,因此應該使用ArrayList代替*

ArrayList<String> returnVal = new ArrayList<>();

*請參閱API,以了解應使用哪些方法向其添加對象

您的returnVal為null, String[] returnVal = null; 並嘗試寫它。 如果您事先知道行數,則將其初始化為returnVal = new String [N_LINES]; ,並更改循環條件以考慮已讀取的數字行。 否則,您可以使用字符串列表並在閱讀時附加到字符串列表:

List<String> returnVal = new ArrayList<>();
...
while((line = br.readLine()) != null) {
    returnVal.add(line);
}

與原始問題無關,但仍然: br.close(); 應該在finally ,如果您使用1.7,則可以從try-with-resources中受益:

List<String> returnVal = new ArrayList<>();
try(BufferedReader br = 
    new BufferedReader(new FileReader(new File(filename)))) {
    while((line = br.readLine()) != null) {
        returnVal.add(line);
    }
} catch (Exception e) {
    debug.error("Unable to read file '"+filename+"'");
    debug.message(e.toString());
}

暫無
暫無

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

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