用于“管道”的Java习惯用语 [英] Java idiom for "piping"

查看:136
本文介绍了用于“管道”的Java习惯用语的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有更简洁/标准的习惯用法(例如,JDK方法)用于输出Java输出到输出?

Is there a more concise/standard idiom (e.g., a JDK method) for "piping" an input to an output in Java than the following?


public void pipe(Reader in, Writer out) {
    CharBuffer buf = CharBuffer.allocate(DEFAULT_BUFFER_SIZE);
    while( in.read(buf) >= 0 ) {
      out.append(buf.flip());
      buf.clear();
    }
}

请注意读者 Writer 给定。正确答案将演示如何在和 out 中取并形成一个管道(最好不超过1或2)方法调用)。我将接受答案中的 out InputStream OutputStream (最好转换自/到读者 / 作家)。我不接受或 out 中的是<$ c c的子类的答案$ c> Reader / InputStream Writer / OutputStrem

Please note the Reader and Writer are given. The correct answer will demonstrate how to take in and out and form a pipe (preferably with no more than 1 or 2 method calls). I will accept answers where in and out are an InputStream and an OutputStream (preferably with a conversion from/to Reader/Writer). I will not accept answers where either in or out is a subclass of Reader/InputStream or Writer/OutputStrem.

推荐答案

IOUtils 有一些 utilily方法,完全符合您的需要。

IOUtils from the Apache Commons project has a number of utilily methods that do exactly what you need.

IOUtils.copy(in,out) )将执行输出的所有输入的缓冲副本。如果您的代码库中有多个位置需要 Stream Reader / Writer 处理,使用IOUtils可能是一个好主意。

IOUtils.copy(in, out) will perform a buffered copy of all input to the output. If there is more than one spot in your codebase that requires Stream or Reader/Writer handling, using IOUtils could be a good idea.

这篇关于用于“管道”的Java习惯用语的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆