apa*_*846 1 java inputstream bytearrayinputstream ioutils
这是我的文件内容丢失的代码流,我认为可能是 IOUtils.toByteArray() 行有问题,请指导这里实际出了什么问题。
文件内容丢失:
InputStream stream = someClient.downloadApi(fileId);
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();
FileUtils.copyInputStreamToFile(stream,file);
int length = (int)file.length();
Run Code Online (Sandbox Code Playgroud)
现在这里的长度值是0基本上没有内容。让我告诉你,从 downloadApi() 接收到的 inputStream 肯定有内容。但是如果我尝试在代码中进行以下修改,那么我就会得到文件的长度。
文件内容不会丢失:
InputStream stream = someClient.downloadApi(fileId);
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;
stream = new ByteArrayInputStream(bytes); //Again converted bytes to stream
File file = new File(filePath+fileName);
file.createNewFile();
FileUtils.copyInputStreamToFile(stream,file);
int length = (int)file.length();
Run Code Online (Sandbox Code Playgroud)
现在我正在获取文件内容。有人能说出第一个代码片段中的技术错误吗?
TIA
不,它没有。
您的代码的第一个版本(在下面复制并添加了一些注释)失败,因为您正在从已经位于流位置末尾的流中读取。
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();
Run Code Online (Sandbox Code Playgroud)
当您尝试从位于流末尾的流中进行复制时,您会得到 ... 零字节。这意味着你会得到一个空的输出文件。