How to resolve inability to close FileStream

I have a closed file at the end and try, but code analysis warned me that:

  • Possible error closing FileOutputStream

  • Possible failure to close PrintWriter

  • Possible error closing OutputStreamWriter

Why might a crash happen? How can I ensure to close FileStream? Thank!

public void writeFile(String filepath)
{
    BufferedWriter bw = null;
    PrintWriter pw = null;
    try {
        File file = new File(filepath);
        bfw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
        pw = new PrintWriter(bfw);

     //do something

    }catch(Exception e){
        e.printStackTrace();
    }
    finally{
        try{
            bfw.close();
            pw.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
}
+4
source share
3 answers

Why might a crash happen?

   finally{
            try{
                bfw.close();   <== exception occured here
                pw.close();    <== this is not execute
            }catch(Exception e){
                e.printStackTrace();
            }
        }

See your finally block,

What if an exception occurs in bfw.close();?

`pw.close();` will never execute. And this leads to resource leak 

How can I ensure to close FileStream?

- , - try catch. , , , Apache commons IO package

:

try{

   ........
} finally {
    IOUtils.closeQuietly(bfw);
    IOUtils.closeQuietly(pw);
}

, java 7

+2

Java-7 , try with resources

File file = new File(filepath);
try(BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), "UTF-8"));
    PrintWriter pw = new PrintWriter(bfw);)
{
    ...
}
catch(Exception exception) //This is optional
{
    exception.printStackTrace();
}

catch finally try-with-resources, try.

+3

If an exception occurs while closing bw, you do not close pw. Try the following:

finally{
    try{
        bw.close();
    } catch(Exception e){
        e.printStackTrace();
    } finally {
        pw.close();
    }
}
0
source

Source: https://habr.com/ru/post/1695500/


All Articles