我们在有些时候,使用网站下载的文件,会是以流的方式接收,而还有些时候,原文件格式为压缩包文件,这时,我们再使用InputStream/OutputStream或者FileInutStram/FileOutputStream来接收或者解析的话,就无法打开下载后的压缩文件,那么,下载的压缩文件流(压缩包流)怎么能打开呢?
答案很简单:使用ZipInputStream/FileOutputStream方式来接
首先,我们将获取到的InputStream流转换成ZipInputStream
然后,用zipInputStream.getNextEntry()方法获取内容,并判断是否是文件或文件夹并创建
最后,用FileOutputStream.write()方法来写入到创建的文件或文件夹中
完成之后,切记要记得close关闭处理
下面,为实例代码:
InputStream inputStream = result.getObjectContent() //获取的InputStream流;
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
byte[] buffer = new byte[1024];
ZipEntry zipEntry;
int len;
File zipfile = new File(StringUtil.DownloadPicUrl+"/"+ get.getObjectKey());
if(zipfile.exists()){
zipfile.delete();
}else {
zipfile.mkdirs();
}
try {
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
String entryName = zipEntry.getName();
if (zipEntry.isDirectory()) {
entryName = entryName.substring(0, entryName.length() - 1);
File folder = new File(zipfile.getAbsolutePath() + File.separator+ entryName);
folder.mkdirs();
} else {
String fileName=zipfile.getAbsolutePath() + File.separator + entryName;
File file1 = new File(fileName);
file1.createNewFile();
FileOutputStream fileOut = new FileOutputStream(file1);
while ((len = zipInputStream.read(buffer)) > 0) {
fileOut.write(buffer, 0, len);
// total+=buffer;
}
fileOut.close();
}
zipInputStream.closeEntry();
}
zipInputStream.close();
} catch (IOException e) {
e.printStackTrace();
RingLog.e(e.toString());
}
以上,为个人见解,如有不同看法或更好的处理方式,请评论区留下您宝贵的建议,非常感谢!!!