How to Close Stream After Use? in Java


Streams have a BaseStream.close() method and implement AutoCloseable, but nearly all stream instances do not actually need to be closed after use.

Source Code

package com.beginner.examples;

import java.io.FileInputStream;
import java.io.IOException;
import java.util.List;
import java.util.function.Predicate;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamExample {

	public static void main(String[] args) throws IOException {
		//Get a Stream object
		Stream stream = Stream.of("a", "b", "c", "d");

		List letters = stream.filter(new Predicate() {

			@Override
			public boolean test(String t) {
				// TODO Auto-generated method stub
				return !t.equals("b");
			}
		}).collect(Collectors.toList());
	
		System.out.println(letters);

		// This Stream doesn't have to be shut down
		//stream.close();
		
		FileInputStream stream2 =new FileInputStream("text.txt");
		
		byte[] buff = new byte[1024];
		
		int len=0;
		while((len=stream2.read(buff))!=-1)
		{
			
			System.out.println(new String(buff,0,len));
			
		}
		//This Stream needs to shut down
		stream2.close();
	}

}

Output:

[a, c, d]
This is a test text.

References

Imported packages in Java documentation:

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments