Java – Try with Resources

try with resources:

  • The resource is as an object that must be closed after finishing the program.
  • The try-with-resources statement ensures that each resource is closed at the end of the statement execution.
import java.io.*;
class Code
{
            public static void main(String[] args) throws Exception
            {
                        try(FileInputStream file = new FileInputStream(“Code.java”))
                        {
                                    int ch;
                                    while((ch=file.read()) != -1){
                                                System.out.print((char)ch);
                                    }
                        }
            }
}
Scroll to Top