try-with-resource automatically closes the resources of the AutoClosable interface

Common classes that implement the AutoCloseable interface are:

BufferedInputStream, BufferedOutputStream

BufferedReader, BufferedWriter

FileInputStream, FileOutputStream

FileReader, FileWriter

InputStream, OutputStream

PrintWriter, PrintStream

Reader, Writer

Scanner, SSLServerSocker, SSLSocket, etc. etc.

for example

try–catch-finally implementation
Scanner scanner = null;
try {
    scanner = new Scanner(new File("test.txt"));
    while (scanner.hasNext()) {
        System.out.println(scanner.nextLine());
    }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} finally {
    if (scanner != null) {
        scanner.close();
    }
}
try-with-resources implementation
try (Scanner scanner = new Scanner(new File("testRead.txt")); 
PrintWriter writer = new PrintWriter(new File("testWrite.txt"))) {

    while (scanner.hasNext()) {
        writer.print(scanner.nextLine());
    }

}catch (FileNotFoundException e) {
    e.printStackTrace();
}

Read More:

Leave a Reply

Your email address will not be published. Required fields are marked *