Search code examples
javafile-ioiotry-catch

Do I need to use a try-with-resource when using java's java.nio.file.readAllLines?


when using java.nio.file.readAllLines, is there any need to close the resource?

I saw in some examples online that they don't do it.

For example here https://www.programcreek.com/java-api-examples/?class=java.nio.file.Files&method=readAllLines They catch the IOException but they don't close any resource.

Any help would be appreciated, thanks!


Solution

  • TL;DR: no.

    As Turing85 hinted in the comments, it is in the documentation.

    The example that you linked to is using the one-arg Files.readAllLines(). The documentation of that method says:

    This method works as if invoking it were equivalent to evaluating the expression:

        Files.readAllLines(path, StandardCharsets.UTF_8)
    

    The documentation of the two-arg method referred to here says:

    This method ensures that the file is closed when all bytes have been read or an I/O error, or other runtime exception, is thrown.

    So no, there is no need for you to do anything to close the file or other resources. So the example that you read is complete and correct on this point.

    Documentation links