使用Java压缩和解压缩文件夹和文件
发布时间:2020-05-25 00:40:54 所属栏目:Java 来源:互联网
导读:如果我的应用程序想要以动态方式使用 java压缩Resultant文件(文件组),那么 Java中有哪些可用选项? 当我浏览时,我已经使用了java.util.zip包,但还有其他方法可以用它来实现吗? public class FolderZiper { public static void main(String[] a) throws Excep
|
如果我的应用程序想要以动态方式使用
java压缩Resultant文件(文件组),那么
Java中有哪些可用选项?
解决方法public class FolderZiper {
public static void main(String[] a) throws Exception {
zipFolder("c:a","c:a.zip");
}
static public void zipFolder(String srcFolder,String destZipFile) throws Exception {
ZipOutputStream zip = null;
FileOutputStream fileWriter = null;
fileWriter = new FileOutputStream(destZipFile);
zip = new ZipOutputStream(fileWriter);
addFolderToZip("",srcFolder,zip);
zip.flush();
zip.close();
}
static private void addFileToZip(String path,String srcFile,ZipOutputStream zip)
throws Exception {
File folder = new File(srcFile);
if (folder.isDirectory()) {
addFolderToZip(path,srcFile,zip);
} else {
byte[] buf = new byte[1024];
int len;
FileInputStream in = new FileInputStream(srcFile);
zip.putNextEntry(new ZipEntry(path + "/" + folder.getName()));
while ((len = in.read(buf)) > 0) {
zip.write(buf,len);
}
}
}
static private void addFolderToZip(String path,String srcFolder,ZipOutputStream zip)
throws Exception {
File folder = new File(srcFolder);
for (String fileName : folder.list()) {
if (path.equals("")) {
addFileToZip(folder.getName(),srcFolder + "/" + fileName,zip);
} else {
addFileToZip(path + "/" + folder.getName(),zip);
}
}
}
} (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
