문제

When I want to close InputFileStream and OutputFileStream objects, eclipse says that I need to catch IOException so here is my code after catching those exceptions. As you can see I am catching IOException twice. Is there a more simple way that I can have only one block for catching IOException for both in.close() and in.read() ?

public class ByteStream {

public static void main(String[] args) {

    FileInputStream in = null;

    try {

        in = new FileInputStream("testdata.txt");
        int nextByte;
        while((nextByte = in.read()) != -1){
            System.out.println(nextByte + "-");
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (in != null){
            try {
                in.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }
}

}

도움이 되었습니까?

해결책

Use the try-with-resources syntax in Java 7

try (FileInputStream in = new FileInputStream("testdata.txt");){

    int nextByte;
    while ((nextByte = in.read()) != -1) {
        System.out.println(nextByte + "-");
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
} 

the compiler will take care of converting the above code to code that closes the in InputStream, or any other AutoCloseable object declared and instatiated in the () part of the try expression.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top