创建 BufferedReaders 列表
我想要一个可以返回 BufferedReader 对象列表的方法(例如目录中的所有文件):
private List<BufferedReader> getInputReaders(List<String> filenames) {
List<BufferedReader> result = new ArrayList<BufferedReader>();
for(String filename : filenames)
result.add(new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8")));
}
return result;
}
这会严重浪费资源吗?
所有这些流是否会在创建时打开并保持不变,从而占用系统资源?
如果是,我可以在“被动”模式下创建这些阅读器而不实际打开流,还是有任何其他解决方法(这样我就可以安全地构建一个包含数千个阅读器的列表)?
I would like to have a method that would return a list of BufferedReader
objects (for example for all files in a directory):
private List<BufferedReader> getInputReaders(List<String> filenames) {
List<BufferedReader> result = new ArrayList<BufferedReader>();
for(String filename : filenames)
result.add(new BufferedReader(new InputStreamReader(new FileInputStream(filename), "UTF-8")));
}
return result;
}
Will this be a major waste of resources?
Will all those streams be opened at the moment of creation and remain so therefore holding system resources?
If yes, can I create those readers in "passive" mode without actually opening streams, or is there any other workaround (so I can build a List with thousands of readers safely)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
是的,
FileInputStream
的构造函数在其构造函数中调用open()
。open()
是一个本机方法,它很可能会为文件保留一个文件描述符。为什么不返回一个将根据需要打开底层流的列表,而不是立即返回 BufferedReaders 列表呢?您可以创建一个保存文件名的类,并在调用时简单地打开资源。
Yes, the constructor for
FileInputStream
invokesopen()
in its constructor.open()
is a native method, which will most likely reserve a file descriptor for the file.Instead of immediately returning a list of BufferedReaders, why not return a list of something that will open the underlying stream as needed? You can create a class that holds onto a filename and simply open the resource when called.
我很确定这是一个坏主意。您可能会面临消耗所有可用文件描述符的风险,并且如果您不想读取文件,则打开文件读取器是没有意义的。
如果要从文件中读取,请打开阅读器,从文件中读取,然后关闭阅读器。然后,对下一个要读取的文件执行相同的操作。
如果您想要一个独特的抽象来从各种源(URL、文件等)读取数据,那么创建您自己的
Source
接口,以及多个实现来包装要读取的资源(URLSource、FileSource、 ETC。)。仅在从Source
实例读取时打开包装资源上的实际读取器。I'm pretty sure it's a bad idea. You risk to consume all the available file descriptors, and there is no point in opening a reader to a file if you don't want to read from it.
If you want to read from the file, then open a reader, read from the file, and close the reader. Then, do the same for the next file to read from.
If you want a unique abstraction to read from various sources (URLs, files, etc.), then create your own
Source
interface, and multiple implementations which would wrap the resource to read from (URLSource, FileSource, etc.). Only open the actual reader on the wrapped resource when reading from yourSource
instance.是的,这些流在创建后就会立即打开,
避免这种情况的好方法是创建一个 LazyReader 类,该类仅在第一次读取时初始化 Reader
yes those streams will be opened as soon as they are created
good way to avoid this is to create a LazyReader class that only initializes the Reader on first read