Java IO流(四)(Autocloseable接口)

2023-12-13 03:45:37

  1. 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();
????????}
????}
}

文章来源:https://blog.csdn.net/weixin_50083448/article/details/134911778
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。