读取生产者范例中的文本文件

问题描述 投票:0回答:1

[一个任务是在生产者范例中读取文本文件。生产者接口定义如下:

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;
}

然后是问题清单:

  1. 鉴于需要提前阅读文本行,因此如何正确支持hasNext。>>
  2. 如何正确管理例外?
  3. 鉴于在生产者范例中不再提供方便的try-with-resources块,如何正确释放外部资源?
  4. P.S。读取文件的最后一行后,将释放资源。 (它是在之后产生的。)>

    P.P.S。如果有可以用作我的任务指导的库和/或代码参考,请共享。

[一个任务是在生产者范例中读取文本文件。生产者接口定义如下:公共接口Producer {/ ** *产生下一项。 * ...

java io producer-consumer
1个回答
0
投票

快速又肮脏:

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();
        }
    };
}
© www.soinside.com 2019 - 2024. All rights reserved.