问题
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);
}
}
The task is to convert it into a:
public static Producer<String> readTextFileRetProducer(File file, Charset charset) {
// ???
return null;
}
Then there goes a list of issues:
- How to support hasNext properly given that it requires reading a text line in advance.
- How to properly manage exceptions?
- How to properly release external resources given that a handy try-with-resources block would no longer be available in the producer paradigm?
P.S. Resources are to be released after the last line from the file has been read. (It is produced after).
P.P.S. If there are libraries and/or code references I could use as a guide to my task, please share them.
回答1:
Quick and dirty:
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();
}
};
}
来源:https://stackoverflow.com/questions/61008107/reading-a-text-file-in-the-producer-paradigm