Java 流式操作 Stream(14) AutoCloseable实现资源自动释放

 Java 流式操作 Stream(14) AutoCloseable实现资源自动释放

package com.lius.collector;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * AutoCloseable
 * 实现AutoCloseable接口,当调用完毕该实现类后,会自动触发close方法(可以实现对资源的自动释放)
 */
public class autoCloseAbleTest implements AutoCloseable {

    private static URL url;
    private static InputStream inStream;
    @Override
    public void close() throws Exception {
        System.out.println("关闭资源");
        inStream.close();
    }

    public static void main(String[] args) throws Exception {
 
        try(autoCloseAbleTest autoCloseAbleTest = new autoCloseAbleTest()){
            url = new URL("https://www.baidu.com");//创建网络资源定位符
            URLConnection connection = url.openConnection();//获取url连接
            inStream = connection.getInputStream();//获取网络资源输

你可能感兴趣的:(Java8新特性)