gpt4 book ai didi

java - 在 'finally' 语句中返回

转载 作者:行者123 更新时间:2023-12-04 14:51:10 25 4
gpt4 key购买 nike

我正在尝试从文件中读取 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 告诉我这很危险。有哪些选择?我不能将返回放在“try” block 中,因为它不会这样做/它不会关闭“finally” block 中的文件。我需要确保文件将被关闭,并返回我创建的数组列表。有什么想法吗?

最佳答案

I can't put the return in the "try" block because it won't do it / it won't close files in the "finally" block.

错误,如果将 return 放在 try block 中,finally block 仍会执行。因此,您可以在 try block 中返回。

try
{
//your code
return buildingsArr;
}
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);
}

关于java - 在 'finally' 语句中返回,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14147768/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com