Вопрос

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