Reading a text file in the Producer paradigm

社会主义新天地 提交于 2020-04-18 05:48:40

问题


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:

  1. How to support hasNext properly given that it requires reading a text line in advance.
  2. How to properly manage exceptions?
  3. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!