概述
数据输入流、输出流间拷贝
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
/**
* @Description : nio工具类
* @Version : V1.0.0
* @Date : 2021/8/13 17:03
*/
public class NIOUtil {
/**
* 数据从输入流复制到输出流
*
* @param input 输入流
* @param output 输出流
* @return 拷贝字节数
* @throws IOException
*/
public static long copy(InputStream input, OutputStream output) throws IOException {
try (ReadableByteChannel src = Channels.newChannel(input);
WritableByteChannel desc = Channels.newChannel(output)) {
ByteBuffer buffer = ByteBuffer.allocate(FileSysConstant.DEFAULT_BUFFER_SIZE);
long count = 0;
int n;
while (FileSysConstant.EOF != (n = src.read(buffer))) {
buffer.flip();
desc.write(buffer);
buffer.compact();
count += n;
}
// 可能有阻塞的没有写入通道
buffer.flip();
while (buffer.hasRemaining()) {
n = desc.write(buffer);
count += n;
}
return count;
}
}
}
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/100294.html