7.1 introduction

A new feature has been added to Java 7 that provides an alternative way to manage resources by automatically closing files. This feature, sometimes called Automatic Resource Management (ARM), is based on an extended version of the try statement. Automatic resource management is primarily used to prevent inadvertent forgetting to release files (or other resources) when they are no longer needed.

try(Resource declaration to close){// Possible exception statement
}catch(Exception type variable name){// Exception handling statement}...finally{
// The statement that must be executed
}
Copy the code

When the try block ends, the resource is automatically released. So there is no need to display the call to the close() method. This form is also known as a “try statement with resources”.

Note:

(1) Resources declared in try statements are implicitly declared final. Resources are limited to try statements with resources

(2) You can manage multiple resources in a try statement, with each resource starting with “; “. Separate can.

③ The resource to be closed must implement the AutoCloseable interface or its self-interface Closeable

	/** * Automatic resource management: automatically close resources implementing the AutoCloseable interface */
	@Test
	public void test8(a){
		try(FileChannel inChannel = FileChannel.open(Paths.get("1.jpg"), StandardOpenOption.READ);
				FileChannel outChannel = FileChannel.open(Paths.get("2.jpg"), StandardOpenOption.WRITE, StandardOpenOption.CREATE)){
			
			ByteBuffer buf = ByteBuffer.allocate(1024);
			inChannel.read(buf);
			
		}catch(IOException e){
			
		}
	}
Copy the code