gpt4 book ai didi

java - Java 中 InputStream 的多个读取器

转载 作者:搜寻专家 更新时间:2023-10-30 20:58:12 25 4
gpt4 key购买 nike

我有一个 InputStream,我正在从中读取字符。我希望多个读者访问此 InputStream。似乎实现此目的的合理方法是将传入数据写入 StringBuffer 或 StringBuilder,并让多个读取器读取它。不幸的是,StringBufferInputStream 已被弃用。 StringReader 读取字符串,而不是不断更新的可变对象。我有哪些选择?自己写?

最佳答案

注意: My other answer更通用(在我看来更好)。

@dimo414 所述,下面的答案要求第一位读者始终领先于第二位读者。如果您确实是这种情况,那么这个答案可能仍然更可取,因为它建立在标准类之上。


要创建两个独立读取同一源的读取器,您必须确保它们不使用同一流中的数据。

这可以通过组合 TeeInputStream 来实现来自 Apache Commons 和 PipedInputStreamPipedOutputStream如下:

import java.io.*;
import org.apache.commons.io.input.TeeInputStream;
class Test {
public static void main(String[] args) throws IOException {

// Create the source input stream.
InputStream is = new FileInputStream("filename.txt");

// Create a piped input stream for one of the readers.
PipedInputStream in = new PipedInputStream();

// Create a tee-splitter for the other reader.
TeeInputStream tee = new TeeInputStream(is, new PipedOutputStream(in));

// Create the two buffered readers.
BufferedReader br1 = new BufferedReader(new InputStreamReader(tee));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in));

// Do some interleaved reads from them.
System.out.println("One line from br1:");
System.out.println(br1.readLine());
System.out.println();

System.out.println("Two lines from br2:");
System.out.println(br2.readLine());
System.out.println(br2.readLine());
System.out.println();

System.out.println("One line from br1:");
System.out.println(br1.readLine());
System.out.println();
}
}

输出:

One line from br1:
Line1: Lorem ipsum dolor sit amet, <-- reading from start

Two lines from br2:
Line1: Lorem ipsum dolor sit amet, <-- reading from start
Line2: consectetur adipisicing elit,

One line from br1:
Line2: consectetur adipisicing elit, <-- resumes on line 2

关于java - Java 中 InputStream 的多个读取器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5034311/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com