BufferedReader未关闭警告不会消失

时间:2013-08-15 19:04:05

标签: java eclipse warnings bufferedreader

我正在使用BufferedReader,虽然我调用了close()方法,但eclipse仍然给了我一个警告。 如果我在while之前放置close()调用,Eclipse不会给我一个警告,但是在那时代码不起作用。 我的代码中是否有错误,或者还有什么问题? 代码:

    Hashtable<String, Hashtable<String, Integer>> buildingStats = new Hashtable<String, Hashtable<String, Integer>>();
    try 
    {
        BufferedReader br = new BufferedReader(new FileReader(new File("Assets/Setup/Buildings.txt"))); // Sets the buildings values to the values in Buildings.tx
        String line;
        int lineNum = 0;
        while((line = br.readLine()) != null)
        {
            ++lineNum;
            String[] values = line.split(",");
            if (values.length != 3)
                throw new Exception("Invalid data in Assets/Setup/Buildings.txt at line " + lineNum);
            if (buildingStats.containsKey(values[0]))
            {
                buildingStats.get(values[0]).put(values[1], Integer.parseInt(values[2]));
            }
            else 
            {
                buildingStats.put(values[0], new Hashtable<String, Integer>());
                buildingStats.get(values[0]).put(values[1], Integer.parseInt(values[2]));

            }

        }
        br.close();
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
    }
    return buildingStats;

2 个答案:

答案 0 :(得分:5)

你应该把它放在像这样的finally方法中:

BufferedReader br = null;
try {
    br = new BufferedReader(new FileReader(new File("Assets/Setup/Buildings.txt")));
    // do things
} catch (Exception e){
   //Handle exception
} finally {
    try {
        br.close();
    } catch (Exception e){}
}

如果您仍然收到警告,请尝试清理并重建您的eclipse项目。

答案 1 :(得分:1)

声明和close()调用之间的任何内容都可以抛出异常,在这种情况下,不会调用close()。尝试将其放在finally块中。