2

ファイルから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」ブロックに入れることができません。それは、「finally」ブロック内のファイルを閉じないためです。ファイルが閉じられることを確認し、作成した配列リストも返す必要があります。何か案は?

4

3 に答える 3

10

リターンを「try」ブロックに入れることができません。それは、「finally」ブロック内のファイルを閉じないためです。

間違っています。returnをtryブロックに入れると、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);
    }
于 2013-01-03T21:44:56.223 に答える
1

Java 7の使用を開始し、trywithresources句を使用することをお勧めします。http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html

元:

static String readFirstLineFromFile(String path) throws IOException {
    try (BufferedReader br = new BufferedReader(new FileReader(path))) {
        return br.readLine();
    }
}
于 2013-01-03T21:50:50.943 に答える
0

例外をスローするか、値を返す必要があります。

return "File Not Found"これを証明するために必要なのは、ブロックの後にコメントアウトして、finallyコンパイルされないことを確認することだけです。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

public class ReturnFinallyExample
{
    public static void main(final String[] args)
    {
        returnFinally();
    }

    private static String returnFinally()
    {
        try
        {
            final File f = new File("that_does_not_exist!");
            final FileInputStream fis = new FileInputStream(f);
            return "File Found!";
        }
        catch (FileNotFoundException e)
        {
            e.printStackTrace();
        }
        finally
        {
            System.out.println("finally!");
        }
        return "File Not Found!";
    }
}

あなたはreturn後を持っている必要がありfinallyますまたはあなたは次のいずれかをしなければなりません:

メソッドを宣言しthrows FileNotFoundExceptoin、outを再スローFileNotExceptionします。

また

FileNotFoundExceptionで包むthrow new RuntimeException(e)

于 2014-10-20T16:39:45.457 に答える