繁体   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