Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
166 views
in Technique[技术] by (71.8m points)

What is the best, and cleanest way to close a file in Java inside a finally block

I wrote a method to close write to a file. However, a senior developer suggested me to close the file inside the finally block.

This is the method I have:

private static void writetoFiles(String error) {
    try {
        File file = new File("errorcode.txt");
        if (!file.exists()) {
            file.createNewFile();
    } else {
            FileWriter updateerrorcode = new FileWriter("errorcode.txt");
            updateerrorcode.write(error);
            updateerrorcode.close();
     }
    } catch (IOException e) {
    }
}

I read many answers in stackoverflow but all of them seemed a bit too complicated for a simple case like mine. Any suggestions how should I go about this?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The cleanest approach would be to do it using the try-with-resources statement as shown below:

private static void writetoFiles(String error) throws IOException {
    //...

    try (FileWriter updateerrorcode = new FileWriter("errorcode.txt")) {
        updateerrorcode.write(error);
    }

    //...
}

Do not catch an exception in a method if it can not handle it:

If the method, writetoFiles can not handle the exception, it should throw the same so that the calling method can handle it appropriately.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...