Java on Line

和java的日子!

  BlogJava :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  8 随笔 :: 0 文章 :: 28 评论 :: 0 Trackbacks
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;

/**
 * 使用java核心类库打包、解包zip文件,不足之处在于压缩中文名的文件时,在压缩包内中文字符是乱码,
 * 在windows下解压后编码正常显示中文,而其他系统下则不能正常还原;
 
*/

 
public class TestZip {

    
/**
     * 定义解压缩zip文件的方法
     * 
@param zipFileName
     * 
@param outputDirectory
     
*/

    
public void unzip(String zipFileName, String outputDirectory) {
        
try {
            ZipInputStream in 
= new ZipInputStream(new FileInputStream(zipFileName));
            
//获取ZipInputStream中的ZipEntry条目,一个zip文件中可能包含多个ZipEntry,
            
//当getNextEntry方法的返回值为null,则代表ZipInputStream中没有下一个ZipEntry,
            
//输入流读取完成;
            ZipEntry z = in.getNextEntry();
            
while (z != null{
                System.out.println(
"unziping " + z.getName());
                
//创建以zip包文件名为目录名的根目录
                File f = new File(outputDirectory);
                f.mkdir();
                
if (z.isDirectory()) {
                    String name 
= z.getName();
                    name 
= name.substring(0, name.length() - 1);
                    System.out.println(
"name " + name);
                    f 
= new File(outputDirectory + File.separator + name);
                    f.mkdir();
                    System.out.println(
"mkdir " + outputDirectory + File.separator + name);
                }

                
else {
                    f 
= new File(outputDirectory + File.separator + z.getName());
                    f.createNewFile();
                    FileOutputStream out 
= new FileOutputStream(f);
                    
int b;
                    
while ((b = in.read()) != -1{
                        out.write(b);
                    }

                    out.close();
                }

                
//读取下一个ZipEntry
                z = in.getNextEntry();
            }

            in.close();
        }

        
catch (Exception e) {
            
// TODO 自动生成 catch 块
            e.printStackTrace();
        }

    }


    
public static void main(String[] args) throws Exception{
        TestZip t 
= new TestZip();
        t.unzip(
"c:/a.zip""c:/b");
        
//解压C盘下的a.zip文件放到C盘下的b文件夹里
        
//一定要注意a.zip文件要经java程序压缩出来的文件,这个程序才可以解压
    }

}
posted on 2007-08-24 16:29 陈东 阅读(3270) 评论(3)  编辑  收藏 所属分类: Java基础

评论

# re: 用java解压文件夹 2008-07-02 19:59 1111111
错误的
  回复  更多评论
  

# re: 用java解压文件夹 2008-10-06 19:41 re
非常好用,顶  回复  更多评论
  

# re: 用java解压文件夹 2009-02-13 12:25 huzheng
就是太慢!!!请问怎样才能快点!!!
  回复  更多评论
  


只有注册用户登录后才能发表评论。


网站导航: