概述
数据输入流、输出流间拷贝
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;
public class NIOUtil {
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;
}
}
}