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:
- [Solved] Read the resources resource and convert it to file error: java.io.filenotfoundexception
- Resources is configured in the build of Maven project to prevent the failure of resource export
- [Solved] SpringBoot Pack Project: Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources
- [Solved] IDEA try-with-resources Error: AutoCloseable
- Initializingbean Interface & Applicationcontextaware Interface in Springboot
- The java springboot websocket service server actively closes the connection and causes java.io.EOFException to be thrown
- [Solved] Error:maven-resources-production:ruoyi-ywjs: java.lang.NegativeArraySizeException
- [Solved] Resource compilation failed (Failed to compile values resource file…
- Eclipse Error: There are no resources that can be added or removed from the server.
- [Solved] Spring Boot Package Error: Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0
- [Solved] Error:Maven Resources Compiler: Maven project configuration required for module ‘XX‘ isn‘t available
- Abstract method and static method of java interface
- [Solved] HttpPost Call https Interface error: PKIX path building failed
- [Solved] BindingException: Type interface XXX is not known to the MapperRegistry
- [Solved] Mybatis Error: Could not find resource mybatis-conf.xml
- jasypt springboot Error: Error creating bean with name ‘enableEncryptablePropertySourcesPostProcessor’ defined in class path resource
- [Solved] Failed to load resource: the server responded with a status of 404 ()
- Annotation @resource & @Autowired introduces Spring bean error
- Error creating bean with name ‘servletEndpointRegistrar‘ defined in class path resource
- [Solved] seata:Error creating bean with name ‘globalTransactionScanner‘ defined in class path resource