首页 > 系统 > Android > 正文

Android文件下载,解压zip文件,清空文件夹

2019-11-09 13:54:15
字体:
来源:转载
供稿:网友
//保存retrofit下载下来的ResponseBody文件 public static File writeResponseBodyToDisk(okhttp3.ResponseBody body, String name) { try { File myDir = new File(Environment.getExternalStorageDirectory().getPath() + File.separator + "YourRootFile"); if (!myDir.exists()) { myDir.mkdirs(); } File file = new File(myDir.getAbsolutePath(), name); LogUtil.i("file download: " + file.getAbsolutePath()); InputStream inputStream = null; OutputStream outputStream = null; try { byte[] buffer = new byte[4096]; inputStream = body.byteStream(); outputStream = new FileOutputStream(file); int read; while ((read = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, read); } outputStream.flush(); return file; } catch (IOException e) { return file; } finally { if (inputStream != null) { inputStream.close(); } if (outputStream != null) { outputStream.close(); } } } catch (IOException e) { return null; } }//解压下载的zip包 public static void unZipFolder(String archive, String decomPRessDir) { try { BufferedInputStream bi; ZipFile zf = new ZipFile(archive); Enumeration e = zf.entries(); while (e.hasMoreElements()) { ZipEntry ze2 = (ZipEntry) e.nextElement(); String entryName = ze2.getName(); String path = decompressDir + "/" + entryName; if (ze2.isDirectory()) { LogUtil.i("正在创建解压目录 - " + entryName); File decompressDirFile = new File(path); if (!decompressDirFile.exists()) { decompressDirFile.mkdirs(); } } else { LogUtil.i("正在创建解压文件 - " + entryName); String fileDir = path.substring(0, path.lastIndexOf("/")); File fileDirFile = new File(fileDir); if (!fileDirFile.exists()) { fileDirFile.mkdirs(); } BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(decompressDir + "/" + entryName)); bi = new BufferedInputStream(zf.getInputStream(ze2)); byte[] readContent = new byte[1024]; int readCount = bi.read(readContent); while (readCount != -1) { bos.write(readContent, 0, readCount); readCount = bi.read(readContent); } bos.close(); } } zf.close(); } catch (IOException e) { LogUtil.i("faile to unzip file"); } }//清空下载的文件 public static void clearFile(File file) { if (file.isFile()) { file.delete(); return; } if (file.isDirectory()) { File[] childFile = file.listFiles(); if (childFile == null || childFile.length == 0) { file.delete(); return; } for (File f : childFile) { clearFile(f); } //file.delete(); } }
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表