1000字范文,内容丰富有趣,学习的好帮手!
1000字范文 > JavaDemo——使用java.util.zip压缩和解压

JavaDemo——使用java.util.zip压缩和解压

时间:2020-11-19 23:43:43

相关推荐

JavaDemo——使用java.util.zip压缩和解压

Demo:

/*** 6月20日下午4:59:37*/package testzip;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.util.zip.ZipEntry;import java.util.zip.ZipInputStream;import java.util.zip.ZipOutputStream;/*** @author XWF**/public class TestZip {/*** @param args*/public static void main(String[] args) {doZip();doUnzip();}public static void doZip() {try {//定义生成压缩的文件File zipf = new File("hello.zip");if(!zipf.exists()) {System.out.println("创建新zip文件结果:" + zipf.createNewFile());}ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(zipf));//需要压缩的文件File infile = new File("testzip.txt");FileInputStream fis = new FileInputStream(infile);//设置zip文件里组织结构zos.putNextEntry(new ZipEntry(infile.getName()));//压缩文件里直接用同名文件压缩int len = 0;byte[] b = new byte[1024];while((len = fis.read(b)) > 0) {zos.write(b, 0, len);}fis.close();//在压缩文件里再保存一份testzip.txt的压缩,并换目录和名字zos.putNextEntry(new ZipEntry("newFolder/a.txt"));//压缩文件里有一个叫newFolder的文件夹,里面保存testzip.txt的压缩,并用a.txt命名fis = new FileInputStream(infile);while((len = fis.read(b)) > 0) {zos.write(b, 0, len);}zos.closeEntry();zos.close();fis.close();System.out.println("压缩完成。");} catch (IOException e) {e.printStackTrace();}}public static void doUnzip() {try {File zipFile = new File("hello.zip");ZipInputStream zis = new ZipInputStream(new FileInputStream(zipFile));ZipEntry zipEntry = null;while((zipEntry = zis.getNextEntry()) != null) {System.out.println("zipEntry.getName:" + zipEntry.getName());int index = zipEntry.getName().lastIndexOf("/");String newFileName = zipEntry.getName().substring(index == -1?0:index+1);//去掉压缩包里的文件夹,这里只要文件名File newFile = new File("unzip_"+newFileName);FileOutputStream fos = new FileOutputStream(newFile);int len = 0;byte[] b = new byte[1024];while((len = zis.read(b)) > 0) {fos.write(b, 0, len);fos.flush();}fos.close();}zis.closeEntry();zis.close();System.out.println("解压完成。");} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}

结果:

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。