简体   繁体   English

从输出流到输入流的管道传输

[英]Piping output from an output stream to an input stream

My problem is piping input from one socket to another. 我的问题是将输入从一个插座传递到另一个插座。 Currently, I am using this code: 目前,我正在使用以下代码:

                    for(;;)
                    {
                        try
                        {
                            output2.write(input1.read());
                        }
                        catch(Exception err)
                        {
                            err.printStackTrace();
                        }
                    }

Even though this technically works, is there a faster way to do this? 即使这在技术上可行,是否有更快的方法来做到这一点?

You can use ByteStreams#copy(InputStream, OutputStream) from Google Guava: 您可以从Google Guava使用ByteStreams#copy(InputStream,OutputStream)

try {
    ByteStreams.copy(input1, output2);
} catch (IOException x) {
    x.printStackTrace();
}

Without using any external libraries and without knowing any more than you have an OutputStream and an InputStream, you can use something like this. 在不使用任何外部库的情况下,并且除了对OutputStream和InputStream的了解之外,还可以使用类似的东西。

byte[] buf = new byte[ 1024 ];
int read = 0;
while( ( read = in.read( buf ) ) != -1 ) {
    out.write( buf, 0, read );
}

This gives you the benefits of block moves, instead of single byte moves as in the code you posted. 这为您提供了块移动的好处,而不是像您发布的代码中那样单字节移动。

This can be improved if we had more information on the types of IO streams you are using. 如果我们有更多关于您正在使用的IO流类型的信息,则可以改善这一点。 You could look at Java.NIO which can provide much quicker block moves in the case of files or sockets. 您可以看一下Java.NIO ,它在文件或套接字的情况下可以提供更快的块移动。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM