Java 中的管道或交换输入/输出流

发布于 2024-10-03 12:58:26 字数 497 浏览 0 评论 0原文

分析器类的列表,用于分析输入流的依赖关系,更改一些内容并将其写入输出流:

public Set<Dependency> analyse(InputStream i, OutputStream o);

分析器应该像这样链接:

for(DocumentAnalyser analyser : a) {
 o.getDependencies().addAll(analyser.analyse(in, out));
 in = new ByteArrayInputStream(out.toByteArray());
} 

现在我正在一个 in 是最终的环境中工作。

  1. 有没有更好的方法来“链接”流?
  2. 使用 ByteArrayInputStream 从“out”到“in”的“交换”操作是否昂贵?
  3. 如何处理“in”是最终的问题?

A list of analyser classes which analyse a InputStream for dependencies, changes a few things and write it to an OutputStream:

public Set<Dependency> analyse(InputStream i, OutputStream o);

The analysers should be chained like:

for(DocumentAnalyser analyser : a) {
 o.getDependencies().addAll(analyser.analyse(in, out));
 in = new ByteArrayInputStream(out.toByteArray());
} 

Now I'm working in a environment where in is final.

  1. Is there a better way to "chain" the streams?
  2. Is the "swap" operation from "out" to "in" with ByteArrayInputStream expensive?
  3. How to deal with the problem that "in" is final?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

帅冕 2024-10-10 12:58:26
  1. 使用辅助线程和 java.io.PipedInputStream/java.io.PipedOutputStream 对。
  2. 可能它在大流上表现不佳。
  3. 正如另一个响应中所说,使用本地非最终变量来进行链接

。请注意,通过应用 1.,您不需要担心 2,因为您实际上是在管道流。

  1. Use helper threads and java.io.PipedInputStream/java.io.PipedOutputStream pairs.
  2. Probably it will not perform well on big streams.
  3. As it is said in another response, use a local non-final variable to do the chaining

Note that by applying 1. you do not need to worry about 2 because you are in fact piping the streams.

情未る 2024-10-10 12:58:26

对于问题 2。
我将提供我自己的子类,它可以直接访问 ByteArrayInputStream 和 ByteArrayOutputStream 的缓冲区。这样,您就不会因为在 toByteArray 中进行额外的复制而浪费内存和时间。

对于问题 3。
将其分配给本地非最终变量,

InputStream nonFinalIn = in;
for(DocumentAnalyser analyser : a) {
 o.getDependencies().addAll(analyser.analyse(nonFinalIn, out));
 nonFinalIn = new ByteArrayInputStream(out.toByteArray());
}

但请注意,原始 in 将不再有效(它将位于流末尾)

For question 2.
I would provide my own subclass that has a direct access to ByteArrayInputStream's and ByteArrayOutputStream's buffer. That way you don't waist memory and time by making extra copy in toByteArray.

For question 3.
Assign it to a local non-final variable,

InputStream nonFinalIn = in;
for(DocumentAnalyser analyser : a) {
 o.getDependencies().addAll(analyser.analyse(nonFinalIn, out));
 nonFinalIn = new ByteArrayInputStream(out.toByteArray());
}

Beware, though, that the original in will no longer be valid ( it will be at the end-of-stream )

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文