在Producer范例中读取文本文件 [英] Reading a text file in the Producer paradigm
本文介绍了在Producer范例中读取文本文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有一个任务可以在生产者范例中读取文本文件.生产者接口定义如下:
There is a task to read a text file in a producer paradigm. The producer interface is defined as the following:
public interface Producer<ITEM> {
/**
* Produces the next item.
*
* @return produced item
*/
ITEM next();
/**
* Tells if there are more items available.
*
* @return true if there are more items, false otherwise
*/
boolean hasNext();
}
当前读取文本文件的代码是:
Current code to read the text file is:
public static void readTextFile(File file, Charset charset, Consumer<String> consumer) {
try (InputStreamReader isr = new InputStreamReader(new FileInputStream(file), charset);
BufferedReader in = new BufferedReader(isr, BUFFER_SIZE)) {
String line;
while ((line = in.readLine()) != null) {
consumer.accept(line);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
任务是将其转换为:
public static Producer<String> readTextFileRetProducer(File file, Charset charset) {
// ???
return null;
}
然后是问题列表:
- 鉴于需要提前阅读文本行,因此如何正确支持 hasNext .
- 如何正确管理异常?
- 在生产者范式中不再提供方便的try-with-resources块的情况下,如何正确释放外部资源?
P.S.读取文件的最后一行后,将释放资源. (它是在之后产生的.)
P.S. Resources are to be released after the last line from the file has been read. (It is produced after).
P.P.S.如果有可以用作我的任务指南的库和/或代码引用,请共享它们.
P.P.S. If there are libraries and/or code references I could use as a guide to my task, please share them.
推荐答案
又快又脏:
public static Producer<String> readFile(File file, Charset charset) {
Stream<String> stream;
try {
stream = Files.lines(file.toPath(), charset);
} catch (IOException e) {
throw new UncheckedIOException(e);
}
Iterator<String> iter = stream.iterator();
return new Producer<String>() {
@Override
public boolean hasNext() {
if (!iter.hasNext()) {
stream.close();
return false;
}
return true;
}
@Override
public String next() {
return iter.next();
}
};
}
这篇关于在Producer范例中读取文本文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文