【发布时间】:2013-01-03 21:43:46
【问题描述】:
我正在尝试从文件中读取 ObjectOutputStream 并将其转换为数组列表。 整个事情发生在一个应该读取文件并返回数组列表的方法中:
public static List<Building> readFromDatabase(){
String fileName="database.txt";
FileInputStream fileIStream=null;
ObjectInputStream in=null;
List<Building> buildingsArr=null;
try
{
fileIStream = new FileInputStream(fileName);
in = new ObjectInputStream(fileIStream);
buildingsArr=(ArrayList<Building>)in.readObject();
}
catch(IOException e)
{
e.printStackTrace();
}
catch(ClassNotFoundException e)
{
Console.printPrompt("ArrayList<Building> class not found.");
e.printStackTrace();
}
finally{
Console.printPrompt("Closing file...");
close(in);
close(fileIStream);
return buildingsArr;
}
}
Java 告诉我这很危险。 有哪些替代方案? 我不能将 return 放在“try”块中,因为它不会这样做/它不会关闭“finally”块中的文件。 我需要确保文件将被关闭,并返回我创建的数组列表。 有什么想法吗?
【问题讨论】:
-
为什么不把
return语句放在finally块之后? -
close(fileIStream);可以(实际上应该)被忽略,因为in.close()会关闭它。 -
附带说明,这是很危险的,因为有可能发生这样的事情:
try { return true; } finally { return false; } -
并且关闭(fileOStream) 可以吗?