2 回答

TA貢獻1820條經(jīng)驗 獲得超9個贊
不,它沒有。
您的代碼的第一個版本(在下面復(fù)制了一些添加的評論)失敗,因為您正在從已經(jīng)位于流位置末尾的流中讀取。
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();
當您嘗試從位于流末尾的流中復(fù)制時,您會得到......零字節(jié)。這意味著你得到一個空的輸出文件。

TA貢獻1893條經(jīng)驗 獲得超10個贊
不,這個流應(yīng)該關(guān)閉。
這是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);
添加回答
舉報