2 回答
TA贡献1820条经验 获得超9个赞
不,它没有。
您的代码的第一个版本(在下面复制了一些添加的评论)失败,因为您正在从已经位于流位置末尾的流中读取。
InputStream stream = someClient.downloadApi(fileId);
// This reads the entire stream to the end of stream.
byte[] bytes = IOUtils.toByteArray(stream);
String mimeType = CommonUtils.fileTypeFromByteArray(bytes);
String fileExtension =
FormatToExtensionMapping.getByFormat(mimeType).getExtension();
String filePath = configuration.getDownloadFolder() + "/" ;
String fileName = UUID.randomUUID() + fileExtension;
File file = new File(filePath+fileName);
file.createNewFile();
// Now you attempt to read more data from the stream.
FileUtils.copyInputStreamToFile(stream,file);
int length = (int)file.length();
当您尝试从位于流末尾的流中复制时,您会得到......零字节。这意味着你得到一个空的输出文件。
TA贡献1893条经验 获得超10个赞
不,这个流应该关闭。
这是IOUtils的目标方法:
public static long copyLarge(final InputStream input, final OutputStream output, final byte[] buffer)
throws IOException {
long count = 0;
int n;
while (EOF != (n = input.read(buffer))) {
output.write(buffer, 0, n);
count += n;
}
return count;
}
// create stream and use it
InputStream stream = someClient.downloadApi(fileId);
byte[] bytes = IOUtils.toByteArray(stream);
// then us it again
FileUtils.copyInputStreamToFile(stream,file);
// FIXED VERSION
FileUtils.copyInputStreamToFile(new ByteArrayInputStream(bytes),file);
添加回答
举报
