流的工具类的使用
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import java.io.*;
@Slf4j
public class StreamFileUtil {
private StreamFileUtil (){
}
public static void writeToOutputStream(byte[] bytes, OutputStream outputStream) throws IOException {
if(outputStream==null){
throw new HonlitechRTException("outputStream 输出流不能为空");
}
try (InputStream in = new ByteArrayInputStream(bytes)) {
int len = 0;
byte[] buf = new byte[1024];
while ((len = in.read(buf)) != -1) {
outputStream.write(buf, 0, len);
}
outputStream.flush();
} finally {
outputStream.close();
}
}
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
public static File inputStreamToFile(InputStream ins, String fileName) {
File file=new File(fileName);
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
throw new HonlitechRTException(ExceptionUtils.getMessage(e));
}
return file;
}
public static void inputStreamWriteOutputStream(InputStream ins, OutputStream output) {
try {
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
output.write(buffer, 0, bytesRead);
}
} catch (Exception e) {
throw new HonlitechRTException(ExceptionUtils.getMessage(e));
}finally {
try {
if(output!=null){
output.close();
}
if(ins!=null){
ins.close();
}
} catch (IOException e) {
log.error(ExceptionUtils.getMessage(e));
}
}
}
}