我正在使用 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;
最佳答案
你应该把它放在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 项目。
关于java - BufferedReader 未关闭警告未消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18259800/