자바 가 ZIP 압축 패키지 의 파일 데 이 터 를 읽 습 니 다.

11311 단어 Java
압축 패키지 에서 데 이 터 를 읽 고 연산 해 야 하 는 항목 이 있 습 니 다.처음에는 압축 을 풀 고 읽 으 려 고 했 어 요.직접 읽 은 것 을 찾 았 습 니 다.주로 ZipEntry 를 사 용 했 습 니 다.여러 개의 압축 패 키 지 를 끼 워 넣 어도 이렇게 읽 을 수 있 습 니 다. 압축 패 키 지 를 압축 해제 하 는 것 이 생각 입 니 다.
import java.util.zip.*;
public static String readZip(String fileName) throws IOException{
        ZipFile zip = new ZipFile(fileName);
        File file = new File(fileName);
        String parentZipParent = file.getParent();/            
        File temp = file;
        BufferedInputStream bis = new BufferedInputStream(new FileInputStream(fileName));
        ZipInputStream zis = new ZipInputStream(bis);
        ZipEntry entry ;//                
        StringBuffer sb = new StringBuffer();
        while((entry = zis.getNextEntry())!=null){
            if(entry.isDirectory()){
                //System.out.println("   ");
            }else{
                //System.out.println("file:"+entry.getName());
                if(entry.getName().endsWith("txt")){
                    BufferedReader reader = new BufferedReader(new InputStreamReader(zip.getInputStream(entry)));
                    String line = null;
                    while((line = reader.readLine())!=null){
                        //System.out.println(line);
                    	sb.append(line);
                    }
                } else if (entry.getName().endsWith("zip")){  //        ,           
                	temp = new File(parentZipParent + "\\" + entry.getName());
                	//System.out.println(temp.getAbsolutePath());
                	if (!temp.getParentFile().exists()) {
                    	temp.getParentFile().mkdirs();
                	}
                   	OutputStream os = new FileOutputStream(temp);
                	////  ZipFile getInputStream       ZipEntry    
                	InputStream is = zip.getInputStream(entry);
                	int len = 0;
                	while ((len = is.read()) !=-1) {
                	os.write(len);
                	}
                	sb.append(readZip(temp.getAbsolutePath()));
                }
            }
        }        
        return sb.toString();
    }

좋은 웹페이지 즐겨찾기