背景
我在做上传文件的时候,第一步要读取文件中的数据进行分析校验,第二步,校验通过后需求将源文件上传OSS,然后使用同一个InputStream流,发现上传OSS的文件为0kb了。
本博客同事解决上传OSS文件为0kb等问题
你在网上找的 将InputStream 转化成ByteArrayInputStream 然后再次调用使用,我可以负责任告诉你,没用,已经测试过。以下例句没用的代码:
/**
* 转换为字节数组输入流,可以重复消费流中数据
*
* @param inputStream
* @return
* @throws IOException
*/
public static ByteArrayInputStream toByteArrayInputStream(InputStream inputStream) throws IOException {
if (inputStream instanceof ByteArrayInputStream) {
return (ByteArrayInputStream) inputStream;
}
try (ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
BufferedInputStream br = new BufferedInputStream(inputStream);
byte[] b = new byte[1024];
for (int c; (c = br.read(b)) != -1; ) {
bos.write(b, 0, c);
}
// 主动告知回收
b = null;
br.close();
inputStream.close();
return new ByteArrayInputStream(bos.toByteArray());
}
}
真正解决方案:
private static byte[] cloneInputStream(InputStream input) {
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int len;
while ((len = input.read(buffer)) > -1) {
baos.write(buffer, 0, len);
}
baos.flush();
baos.close()
input.close()
return baos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
调用:
//存入上传文件到OSS
byte[] bytes = cloneInputStream(inputStream);
InputStream fileInputStream = new ByteArrayInputStream(bytes);
AliyunCloudStorageService storageService = new AliyunCloudStorageService(config);
storageService.upload(fileInputStream, fileName, url);
//读取文件
InputStream newInputStream = new ByteArrayInputStream(bytes);
CsvReader csvReader = new CsvReader(new BufferedInputStream(newInputStream), Charset.forName("utf-8"));