开发手册 欢迎您!
软件开发者资料库

Java 读取InputStream并写入OutputStream的方法及示例代码

本文主要介绍Java中,从InputStream输入流中读取数据,然后写入OutputStream输出流中的方法,以及相关的示例代码。

1、使用Guava的ByteStreams.copy()方法

文档ByteStreams.copy()

ByteStreams.copy(inputStream, outputStream);

2、使用read和write实现

private void copyInputStreamToFile( InputStream in, File file ) {    try {        OutputStream out = new FileOutputStream(file);        byte[] buf = new byte[1024];        int len;        while((len=in.read(buf))>0){            out.write(buf,0,len);        }        out.close();        in.close();    } catch (Exception e) {        e.printStackTrace();    }}

或者

// buffer size used for reading and writingprivate static final int BUFFER_SIZE = 8192;/**  * Reads all bytes from an input stream and writes them to an output stream.  */private static long copy(InputStream source, OutputStream sink) throws IOException {    long nread = 0L;    byte[] buf = new byte[BUFFER_SIZE];    int n;    while ((n = source.read(buf)) > 0) {        sink.write(buf, 0, n);        nread += n;    }    return nread;}

或者

try(InputStream inputStream = new FileInputStream("C:\\mov.mp4");    OutputStream outputStream = new FileOutputStream("D:\\mov.mp4")) {    byte[] buffer = new byte[10*1024];    for (int length; (length = inputStream.read(buffer)) != -1; ) {        outputStream.write(buffer, 0, length);    }} catch (FileNotFoundException exception) {    exception.printStackTrace();} catch (IOException ioException) {    ioException.printStackTrace();}

或者

byte[] buffer = new byte[2048];
for (int n = in.read(buffer); n >= 0; n = in.read(buffer))
out.write(buffer, 0, n);

3、使用Spring framework的StreamUtils.copy(in, out)方法

文档

StreamUtils

FileCopyUtils

StreamUtils.copy(inputStream, outputStream);

或者

FileCopyUtils.copy(inputStream, outputStream);

4、使用Commons Net的 Util类

import org.apache.commons.net.io.Util;
Util.copyStream(inputStream, outputStream);

相关文档:

Java 复制克隆(clone)Inputstream的方法及示例代码

Java Inputstream流转换读取成byte[]字节数组方法及示例代码

Java Inputstream流转换读取成String字符串方法及示例代码

Java 使用Stream I/O(Inputstream/OutputStream)读写文件的方法及示例代码