matrix.boot.common.utils.NIOStreamUtil Maven / Gradle / Ivy
package matrix.boot.common.utils;
import matrix.boot.common.exception.ServiceException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* NIO流处理工具
* @author wangcheng
* 2021/8/12
**/
public class NIOStreamUtil {
/**
* 文件流输出文件流
* @param fis 文件输入流
* @param fos 文件输出流
*/
public static void streamWriteStream(FileInputStream fis, FileOutputStream fos) {
FileChannel fileInChannel;
FileChannel fileOutChannel = null;
try {
fileInChannel = fis.getChannel();
fileOutChannel = fos.getChannel();
ByteBuffer buf = ByteBuffer.allocate(1000);
while (fileInChannel.read(buf) != -1) {
buf.flip();
while(true) {
if (fileOutChannel.write(buf) == 0) break;
}
buf.clear();
}
} catch (Exception e) {
throw new ServiceException(e);
} finally {
BIOStreamUtil.closeStream(fileOutChannel);
BIOStreamUtil.closeStream(fileOutChannel);
}
}
}