InputStream转byte[]其实是比较简单的,直接使用IOUtils就可以了:
byte[] bytes = IOUtils.toByteArray(inputStream);
又或者说这样:
public static byte[] toByteArray(InputStream input) throws IOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
byte[] buffer = new byte[1024*4];
int n = 0;
while (-1 != (n = input.read(buffer))) {
output.write(buffer, 0, n);
}
return output.toByteArray();
}
但是需要注意的是,将InputStream粗暴地转成byte[],只适用于文件较小的时候,当如果文件有好几个G,再这样转,内存就要溢出了。
如果我们需要把InputStream保存到本地,在遇见较大的文件时可以试试使用,它会一点点搬,默认一次性应该是读8k左右:
InputStream is = downloadClient.download(downloadDTO);
if(is == null){
LOGGER.info("is == null");
}
//文件下载路径
String tempDirPath = PathTool.absolutePath();
LOGGER.info("file download path:"+tempDirPath);
File tmpDir = new File(tempDirPath);
if (!tmpDir.exists()) {
try {
tmpDir.mkdirs();
} catch (Exception e) {
throw new xxxException(xxxErrorCode.ERR_FILE_CREATE);
}
}
LOGGER.info("file download dirs exist");
File tmpFile = new File(tmpDir, downloadDTO.getFileName());
if (!tmpFile.exists()) {
try {
tmpFile.createNewFile();
} catch (IOException e) {
throw new xxxException(xxxErrorCode.ERR_FILE_CREATE);
}
}
LOGGER.info("file exist");
//保存文件
OutputStream os = null;
try {
os = new FileOutputStream(tmpFile);
if(is != null){
IOUtils.copy(is,os);
}
}catch (FileNotFoundException fileNotFoundException){
throw new xxxException(xxxErrorCode.ERR_FILE_CREATE, fileNotFoundException.getCause());
}catch (IOException e) {
……
} finally {
try {
if (os != null) {
os.close();
}
} catch (IOException e) {
……
}
}