公司有个需求是从ftp下载一个zip,解压后删除zip,结果我发现只下载的话删除没问题,但是解压后就删除不了,网上说的就是流没有正确关闭,但是我的是正确关闭的,后来发现很简单只要一句话zipFile.close();加上删除就没问题了。
/** * 解压 * @param dir 文件地址 * @param targetPath 解压到 */ public static void unZip(String dir,String targetPath){ try { File file=new File(dir); ZipFile zipFile=new ZipFile(file); ZipInputStream zipInputStream=new ZipInputStream(new FileInputStream(file)); ZipEntry zipEntry=null; while((zipEntry = zipInputStream.getNextEntry()) != null){ File outFile = new File(targetPath+File.separator + zipEntry.getName()); if (!outFile.getParentFile().exists()){ outFile.getParentFile().mkdir(); } if (!outFile.exists()){ outFile.createNewFile(); } BufferedInputStream bis=new BufferedInputStream(zipFile.getInputStream(zipEntry)); BufferedOutputStream bos=new BufferedOutputStream(new FileOutputStream(outFile)); byte[] bytes=new byte[1024]; while (true){ int len=bis.read(bytes); if (len==-1){ break; } bos.write(bytes,0,len); } bis.close(); bos.close(); } zipInputStream.close(); zipFile.close();//如果不加上这句话,解压完删除不了 }catch (FileNotFoundException e){ logger.error("file not found {}",e); }catch (IOException e){ logger.error("",e); } }