zip解析

软件包 java.util.zip 的分层结构

主要用到了4个类: ZipInputStream  ZipOutputStream   ZipEntry   ZipFile

ZipFile含有 ZipEntry   可以使用 ZipFile.entrys()  ZipFile.getEntry()函数来获得ZipEntry对象。
如果想读取ZipEntry可使用ZipFile.getInputStream()来获得ZipEntry的流对象。
<pre name="code" class="java">package com.lmk.test.ziptest;

import java.io.IOException;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class ZipTest {
	
	public static void main(String[] args){
		ZipTest test = new ZipTest();
		test.openZipFile();
		
		
	}

	private void openZipFile() {
		// TODO Auto-generated method stub
		ZipFile file = null;
		try {
			file = new ZipFile("d:/lmk.zip");
			info(file.getName());
			info(file.size()+"");
			
			Enumeration<ZipEntry> entrys = (Enumeration<ZipEntry>) file.entries();
//			for (ZipEntry entry = entrys.nextElement();entrys.hasMoreElements();) {
//				info(entry.getName());//注意 这里的getName 不识别汉字。
//				entry = entrys.nextElement();
//			}
			ZipEntry entry = null;
			do{
				entry = entrys.nextElement();
				info(entry.getName()+"  "+entry.isDirectory());//注意 这里的getName 不识别汉字。
				info(entry.getMethod()+"");
				if(entry.getName().endsWith("txt")){
					readZipEntry(file,entry);
				}
			}while(entrys.hasMoreElements());
			file.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			
		}
	}

	private void readZipEntry( ZipFile file, ZipEntry entry) {
		// TODO Auto-generated method stub
		Scanner in = null;
		try {
			in = new Scanner(file.getInputStream(entry));
			while(in.hasNext()){
				info(in.nextLine());
			}
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally{
			in.close();
		}
		
	}

	private void info(String s) {
		// TODO Auto-generated method stub
		System.out.println(s);
	}

}

还有一种读取方法就是使用ZipInputStream对象。
 
 
<pre name="code" class="java">	private void readZipFile() {
		// TODO Auto-generated method stub
		ZipInputStream in = null;
		ZipEntry entry = null;
		int num = 0;
		try {
			in =new ZipInputStream(new FileInputStream("d:/lmk.zip"));
			while((entry = in.getNextEntry())!= null){
				num++;
				if (entry.getName().endsWith("txt")){
					Scanner scan = new Scanner(in);//注意这里直接将ZipInputStream导入
					while(scan.hasNextLine()){
						info(scan.nextLine());
					}
				}
				in.closeEntry();
			}
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}


 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值