Java 8 Should we close the Stream after use?

摘要: Only Streams whose source are an IO channel like Files.lines(Path, Charset) need to be closed.

Only Streams whose source are an IO channel like Files.lines(Path, Charset) need to be closed.

Read this Stream JavaDocs

Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use. Generally, only streams whose source is an IO channel (such as those returned by Files.lines(Path, Charset)) will require closing. Most streams are backed by collections, arrays, or generating functions, which require no special resource management. (If a stream does require closing, it can be declared as a resource in a try-with-resources statement.)

1. For normal Stream like this, the stream instance does not need to be closed after use.

Java8StreamExample.java
package com.mkyong;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8StreamExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("A", "B", "C");
        List<String> filter = stream.filter(x -> !x.equalsIgnoreCase("B"))
			.collect(Collectors.toList());
        // no need close the stream.
        //stream.close();
        System.out.println(filter); // [A, C]

2. For Stream whose source are an IO channel, close it with try-with-resources

Java8StreamIO.java
package com.mkyong;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class Java8StreamIO {
    public static void main(String[] args) {
        String path = "c:\\projects\\app.log";
		// auto close
        try (Stream<String> lines = Files.lines(Paths.get(path))) {
            String content = lines.collect(Collectors.joining(System.lineSeparator()));
        } catch (IOException e) {
            e.printStackTrace();

上一篇: Java Add new line in String
下一篇: Java what is -Xms and -Xmx parameter?
 评论 ( What Do You Think )
名称
邮箱
网址
评论
验证
   
 

 


  • 微信公众号

  • 我的微信

站点声明:

1、一号门博客CMS,由Python, MySQL, Nginx, Wsgi 强力驱动

2、部分文章或者资源来源于互联网, 有时候很难判断是否侵权, 若有侵权, 请联系邮箱:summer@yihaomen.com, 同时欢迎大家注册用户,主动发布无版权争议的 文章/资源.

3、鄂ICP备14001754号-3, 鄂公网安备 42280202422812号