简体   繁体   中英

How to create an InputStream of files that have a certain extension in Java?

I have a lot of files in a directory but I only want to read the ones with a certain extension (say .txt). I want these files added to the same BufferedInputStream so that I can read them in one go. When I call read() at the end of a file, the next one should begin.

It really feels like there should be an obvious answer to this but I had no luck finding it.

You might want to take a look at SequenceInputStream :

A SequenceInputStream represents the logical concatenation of other input streams. It starts out with an ordered collection of input streams and reads from the first one until end of file is reached, whereupon it reads from the second one, and so on, until end of file is reached on the last of the contained input streams.

To me the "obvious answer" is:

Just iterate through all the files in the directory using a proper filter. For each file create a FileInputStream , read it and close it.

I don't think there is an obvious answer to this question.

Probably you need to create a Wrapper InputStream with a list of files you want to read from. Internally you will open/close streams as needed, namely when a file is completely read.

It is not obvious but should not be difficult. This way you can work 'only' with one InputStream for all files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM