2

我正在使用 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;
4

2 回答 2

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 项目。

于 2013-08-15T19:07:28.227 回答
1

声明和调用之间的几乎所有内容都close()可能引发异常,在这种情况下,您close()将不会被调用。试着把它放在一个finally块里。

于 2013-08-15T19:15:04.157 回答