java解压缩文件

xiaoxiao2021-02-28  103

流:ZipInputStream ZipOutputStream

包:java.util.zip

压缩文件:

对文件夹压缩,使用一个输出流,遍历文件夹,多个输入流

参数:zipFileName为压缩文件名称,inputFile为压缩源文件

void zip(String zipFileName, File inputFile) throws Exception { ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName)); zip(out,inputFile); out.close(); } void zip(ZipOutputStream out, File f) throws Exception { if(f.isDirectory()) { //System.out.println(f.getPath()+"--"+f.getAbsolutePath()+"--"+f.getCanonicalPath()); out.putNextEntry(new ZipEntry(f.getPath()+"/")); File[] listFiles = f.listFiles(); for (File file : listFiles) { zip(out,file); } }else { out.putNextEntry(new ZipEntry(f.getPath())); //System.out.println(f+"--"+f.getPath()+"--"+f.getAbsolutePath()+"--"+f.getCanonicalPath()); FileInputStream in = new FileInputStream(f); int b; while((b=in.read())!=-1) { out.write(b); } in.close(); } }

解压文件:

f.createNewFile()只是创建了空文件,真正的解压需要使用输出流操作

void dezip() throws Exception { ZipInputStream in = new ZipInputStream(new FileInputStream("E:\\py.zip")); ZipEntry entry = in.getNextEntry(); while(entry!=null) { System.out.println(entry.getName()); File f = new File(entry.getName()); if(!f.exists()) { if(entry.isDirectory()) f.mkdirs(); else f.createNewFile(); } entry = in.getNextEntry(); } in.close(); }

转载请注明原文地址: https://www.6miu.com/read-21542.html

最新回复(0)