下面的分别是写和读zip文件,其中写是递归的,功能完备了。读只是读根目录的,缺少递归。
而且没有涉及中文问题:
- import java.io.*;
- import java.util.zip.*;
-
- public class Zip {
- static final int BUFFER = 2048;
- static boolean flag = false;
-
- public static void main(String args[])throws IOException{
- File file= new File("D:/Temp");
- ZipSubdirectory(file);
- FileInputStream file1 = new FileInputStream(ZipSubdirectory(file));
- System.out.println(file1.toString());
- }
-
- public static File ZipSubdirectory(File myDir)throws IOException{
-
- BufferedInputStream origin = null;
-
- File zipFile=new File("D:/"+myDir.getName()+".zip");
- FileOutputStream fos=new FileOutputStream(zipFile);
- ZipOutputStream out=new ZipOutputStream(new BufferedOutputStream(fos,BUFFER));
-
- File dirContents[]=myDir.listFiles();
-
- File tempFile=null;
- try{
-
- for(int i=0;i < dirContents.length; i++){
-
- if(dirContents[i].isDirectory()){
- tempFile = ZipSubdirectory(dirContents[i]);
- flag=true;
- }
-
- else {
- tempFile=dirContents[i];
-
- flag = false;
- }
- System.out.println("Compress file: "+tempFile.getName());
- FileInputStream fis = new FileInputStream(tempFile);
- origin = new BufferedInputStream(fis,BUFFER);
-
- ZipEntry entry = new ZipEntry(tempFile.getName());
- byte data[]= new byte[BUFFER];
- int count;
-
- out.putNextEntry(entry);
-
- while((count=origin.read(data,0,BUFFER))!=-1){
- out.write(data,0,count);
- }
-
- if(flag==true){
- flag = tempFile.delete();
- System.out.println("Delete file:"+tempFile.getName()+flag);
- }
-
- origin.close();
- }
- out.close();
- } catch(Exception e){
- System.out.println(e);
- }
-
- return zipFile;
- }
- }
- import java.io.BufferedInputStream;
- import java.io.BufferedOutputStream;
-
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
-
- import java.util.zip.ZipEntry;
- import java.util.zip.ZipInputStream;
- import java.util.zip.ZipOutputStream;
-
- public class Test {
-
-
- public static void main(String[] args) {
- readFileAndWriteZip();
- unZipFile();
- }
-
- public static void unZipFile() {
- try{
- int BUFFER = 1024;
- BufferedOutputStream dest = null;
- FileInputStream fis = new FileInputStream("D:/Temp.zip");
- ZipInputStream zis = new ZipInputStream(new BufferedInputStream(fis));
- ZipEntry entry;
- while ((entry = zis.getNextEntry()) != null) {
- System.out.println("Extracting: " + entry);
- int count;
- byte data[] = new byte[1024];
- FileOutputStream fos = new FileOutputStream("D:/"+entry.getName());
- dest = new BufferedOutputStream(fos, BUFFER);
- while ((count = zis.read(data, 0, BUFFER)) != -1) {
- dest.write(data, 0, count);
- }
- dest.flush();
- dest.close();
- }
- zis.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
-
- }
-
- public static void readFileAndWriteZip() {
-
- try {
-
- } catch (Exception ex){
- System.err.println(ex.toString());
- }
- }
-
-
-
- }
测试通过的。