[一个任务是在生产者范例中读取文本文件。生产者接口定义如下:
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();
}
读取文本文件的当前代码是:
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)) {
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;
}
然后是问题清单:
P.S。读取文件的最后一行后,将释放资源。 (它是在之后产生的。)>
P.P.S。如果有可以用作我的任务指导的库和/或代码参考,请共享。
[一个任务是在生产者范例中读取文本文件。生产者接口定义如下:公共接口Producer
快速又肮脏:
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();
}
};
}