近日,在别的Java论坛上看到有人贴出的Java解压Zip的源码,据说是有问题,小弟昨日小做测试,没有问题.
现在,我贴出经过测试后的源码供大家研究学习:
package com.hand;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
public class Zip {
/**
* @param args
*/
public static int iCompressLevel; //压缩比 取值范围为0~9
public static boolean bOverWrite; //是否覆盖同名文件 取值范围为True和False
private static ArrayList allFiles = new ArrayList();
public static String sErrorMessage;
public static ArrayList Ectract(String sZipPathFile, String sDestPath){
ArrayList allFileName = new ArrayList();
try{
//先指定压缩档的位置和档名,建立FileInputStream对象
FileInputStream fins = new FileInputStream(sZipPathFile);
//将fins传入ZipInputStream中
ZipInputStream zins = new ZipInputStream(fins);
ZipEntry ze = null;
byte ch[] = new byte[256];
while((ze = zins.getNextEntry()) != null){
File zfile = new File(sDestPath + ze.getName());
File fpath = new File(zfile.getParentFile().getPath());
if(ze.isDirectory()){
if(!zfile.exists())
zfile.mkdirs();
zins.closeEntry();
}else{
if(!fpath.exists())
fpath.mkdirs();
FileOutputStream fouts = new FileOutputStream(zfile);
int i;
allFileName.add(zfile.getAbsolutePath());
while((i = zins.read(ch)) != -1)
fouts.write(ch,0,i);
zins.closeEntry();
fouts.close();
}
}
fins.close();
zins.close();
sErrorMessage = "OK";
}catch(Exception e){
System.err.println("Extract error:" + e.getMessage());
sErrorMessage = e.getMessage();
}
allFiles.clear();
return allFileName;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Zip z = new Zip();
ArrayList a = new ArrayList();
a = z.Ectract("c:\\src.zip", "c:\\");
System.out.println(a.size());
}
}
注: 解压C盘根目录下文件src.zip到C盘根目录.
另:附录一将一个字符串分割为子字符串,然后将结果作为字符串数组返回的有用的Java程序.关于split()方法的使用
package com.hand.tools;
public class SplitDemo {
public static String[] ss = new String[20];
public SplitDemo(){
String s = "The test in String start action success";
//在每个空格字符处进行分解
ss = s.split(" ");
}
/**
* @param args
* 将一个字符串分割为子字符串,然后将结果作为字符串数组返回。
* java.lang.string.split
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SplitDemo demo = new SplitDemo();
System.out.println("test the length="+ss.length);
for(int i=0; i < ss.length; i++){
System.out.println(ss[i]);
}
System.out.println("the last element is : "+ ss[6]);
}
}
运行返回结果:
test the length=7
The
test
in
String
start
action
success
the last element is : success