简体   繁体   English

如何在Java中创建具有特定扩展名的文件的InputStream?

[英]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). 我的目录中有很多文件,但我只想读取具有特定扩展名的文件(例如.txt)。 I want these files added to the same BufferedInputStream so that I can read them in one go. 我希望将这些文件添加到相同的BufferedInputStream中,以便一次性读取它们。 When I call read() at the end of a file, the next one should begin. 当我在文件末尾调用read()时,下一个应该开始。

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 : 您可能需要看一下SequenceInputStream

A SequenceInputStream represents the logical concatenation of other input streams. SequenceInputStream表示其他输入流的逻辑串联。 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. 为每个文件创建一个FileInputStream ,将其读取并关闭。

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. 可能需要创建一个Wrapper InputStream,其中包含要读取的文件列表。 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. 这样,您可以“仅”对所有文件使用一个InputStream。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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