返回'finally'语句

Jja*_*ang 2 java file stream

我正在尝试从文件中读取ObjectOutputStream并将其转换为arraylist.整个事情发生在一个应该读取文件并返回数组列表的方法中:

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;
    }
}
Run Code Online (Sandbox Code Playgroud)

Java告诉我这很危险.有哪些替代方案?我不能把返回放在"try"块中,因为它不会这样做/它不会关闭"finally"块中的文件.我需要确保文件将被关闭,并返回我创建的数组列表.有任何想法吗?

Per*_*ror 10

我不能把返回放在"try"块中,因为它不会这样做/它不会关闭"finally"块中的文件.

错了,如果你在try块中放入return,finally块仍会执行.因此,您可以在try块中返回.

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);
    }
Run Code Online (Sandbox Code Playgroud)