您的位置:首页 > 编程语言 > Java开发

JAVA 压缩文件和解压文件

2015-08-11 10:17 435 查看

JAVA 压缩文件和解压文件

使用到Apache的一个开源Jar包ant-1.9.4.jar

Java 压缩文件

public  void zip(List<File> files, String zipFilepath) throws BuildException, RuntimeExceptioan {
Zip zip = new Zip();
for (File file : files) {
Project proj = new Project();
FileSet fileSet = new FileSet();
fileSet.setProject(proj);
fileSet.setFile(file);  //这里是将给定的file压缩起来,也可以将给定的dir压缩起来,需要使用fileSet.setDir()
zip.setProject(proj);
zip.addFileset(fileSet);
}
zip.setDestFile(new File(zipFilepath));
zip.setEncoding("utf-8");
zip.execute();
}


压缩文件就是这样,可以将给定的文件压缩起来,也可以将给定的dir压缩起来。

Java解压文件

public static void unZipFiles(File zipFile){
String unZipPath = zipFile.getParentFile().getPath() + "/" + zipFile.getName().substring(0, zipFile.getName().lastIndexOf("."));
try {
ZipFile zf = new ZipFile(zipFile);
ZipInputStream zipInputStream = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry zipEntry = null;
while((zipEntry = zipInputStream.getNextEntry()) != null){
String fileName = zipEntry.getName();
File temp = new File(unZipPath + "/" + fileName);
System.out.println(temp.getPath());
if (!temp.getParentFile().exists()) {
temp.getParentFile().mkdirs();
}
OutputStream os = new FileOutputStream(temp);
InputStream is = zf.getInputStream(zipEntry);
int len = 0;
while((len = is.read()) != -1){
os.write(len);
}
os.close();
is.close();
}
zipInputStream.close();
} catch (ZipException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


这个就是解压文件。

仅供自己参考
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: