How to use try-with-resources in nested function in java?

120 Views Asked by At

I noticed that if I don't call myBufferedWriter.close(), my content will not appear in the target file. What if the program ends accidentally before reaching myBufferedWriter.close()? How to avoid losing data that are already in the buffer but not written to the file yet?

Edit: I have found the simple use case of try-with-resources, but my code is like the following

public class myClass{
    Map<String, BufferedWriter> writerMap = new HashMap<>();
    public void write(···){
        //call this.create() here
        ···
        //normally, the writer will close here

    }
    
    public void create(···){
        //BufferedWriter is created here, and saved into writerMap
        ···
    }


}

Where is the best place to use the try-with-resources statement?

2

There are 2 best solutions below

2
Inazense On

You can handle it with a try - catch - finally sentence. Something like:

try {
    // Do things
} catch (Exception e) {
    e.printStackTrace();
} finally {
    if (myBufferedWriter != null) {
        try {
            myBufferedWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
2
peterulb On

Your best bet is The try-with-resources Statement.

The try-with-resources statement ensures that each resource is closed at the end of the statement. [...] the try-with-resources statement contains [...] declarations that are separated by a semicolon[...]. When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the [...] objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

public static void writeToFileZipFileContents(String zipFileName,
                                           String outputFileName)
                                           throws java.io.IOException {

    java.nio.charset.Charset charset =
         java.nio.charset.StandardCharsets.US_ASCII;
    java.nio.file.Path outputFilePath =
         java.nio.file.Paths.get(outputFileName);

    // Open zip file and create output file with 
    // try-with-resources statement

    try (
        java.util.zip.ZipFile zf =
             new java.util.zip.ZipFile(zipFileName);
        java.io.BufferedWriter writer = 
            java.nio.file.Files.newBufferedWriter(outputFilePath, charset)
    ) {
        // Enumerate each entry
        for (java.util.Enumeration entries =
                                zf.entries(); entries.hasMoreElements();) {
            // Get the entry name and write it to the output file
            String newLine = System.getProperty("line.separator");
            String zipEntryName =
                 ((java.util.zip.ZipEntry)entries.nextElement()).getName() +
                 newLine;
            writer.write(zipEntryName, 0, zipEntryName.length());
        }
    }
}