【问题标题】:BufferedReader not closed warning not disappearingBufferedReader 未关闭警告未消失
【发布时间】:2013-08-15 19:04:04
【问题描述】:

我使用的是 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;

【问题讨论】:

  • 试试把 br.close();在finally 块中
  • 终于要关闭了。如果在到达该行之前抛出异常怎么办?

标签: java eclipse warnings bufferedreader


【解决方案1】:

你应该像这样把它放在 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 项目。

【讨论】:

  • 吞下close()抛出的异常是个坏主意。
  • @LouisWasserman 我一直认为它是,尝试关闭,如果你不能关闭它已经关闭或者没有办法关闭连接。即使你再次调用close,你也会得到同样的错误。
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    相关资源
    最近更新 更多