- Autocloseable接口
实现Autocloseable的IO类在特定的情况下,可以自动释放资源。
JDK7时的写法:
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;public class ByteStreamDemoJDK7 {public static void main(String[] args) {/*JDK7:IO流中捕获异常的写法try后面的小括号中写创建对象的代码,注意:只有实现了AutoCloseable接口的类,才能在小括号中创建对象。try(){}catch(){}*/// 1.创建对象try (FileInputStream fis = new FileInputStream("D:\\itheima\\movie.mp4");FileOutputStream fos = new FileOutputStream("myio\\copy.mp4")) { // 对象之间用分号;隔开//2.拷贝int len;byte[] bytes = new byte[1024 * 1024 * 5];while ((len = fis.read(bytes)) != -1) {fos.write(bytes, 0, len);}} catch (IOException e) {e.printStackTrace();}}
}
JDK9时的写法:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;public class ByteStreamDemoJDK9 {public static void main(String[] args) throws FileNotFoundException {/*JDK9的写法*/// 1.创建对象FileInputStream fis = new FileInputStream("D:\\itheima\\movie.mp4");FileOutputStream fos = new FileOutputStream("myio\\copy.mp4");try (fis; fos) { // 对象之间用分号;隔开//2.拷贝int len;byte[] bytes = new byte[1024 * 1024 * 5];while ((len = fis.read(bytes)) != -1) {fos.write(bytes, 0, len);}} catch (IOException e) {e.printStackTrace();}}
}