[英]zip4j zipping for files and folders in java
我希望用Java创建一个zip程序,其中的zip文件和文件夹表示这样的结构-
我使用zip4j开放源代码,我已经将所有文件(具有绝对路径)收集在一个列表中,然后将其提供给zip,但仅在my.zip中才压缩文件-
如何在压缩和解压缩时保留与本地较早版本相同的结构。 请建议是否有其他开放源代码可以像其他Windows zip程序一样帮助我对相同结构的文件和文件夹进行zip / unzip。
代码如下-
public class CreateZipWithOutputStreams {
ArrayList filesToAdd = new ArrayList();
public void CreateZipWithOutputStreams(String sAbsolutePath) {
ZipOutputStream outputStream = null;
InputStream inputStream = null;
try {
ArrayList arrLocal = exploredFolder(sAbsolutePath);
outputStream = new ZipOutputStream(new FileOutputStream(new File("c:\\ZipTest\\CreateZipFileWithOutputStreams.zip")));
ZipParameters parameters = new ZipParameters();
parameters.setCompressionMethod(Zip4jConstants.COMP_DEFLATE);
parameters.setCompressionLevel(Zip4jConstants.DEFLATE_LEVEL_NORMAL);
parameters.setEncryptFiles(true);
parameters.setEncryptionMethod(Zip4jConstants.ENC_METHOD_AES);
parameters.setAesKeyStrength(Zip4jConstants.AES_STRENGTH_256);
parameters.setPassword("neelam");
for (int i = 0; i < arrLocal.size(); i++) {
File file = (File) arrLocal.get(i);
outputStream.putNextEntry(file, parameters);
if (file.isDirectory()) {
outputStream.closeEntry();
continue;
}
inputStream = new FileInputStream(file);
byte[] readBuff = new byte[4096];
int readLen = -1;
while ((readLen = inputStream.read(readBuff)) != -1) {
outputStream.write(readBuff, 0, readLen);
}
outputStream.closeEntry();
inputStream.close();
}
outputStream.finish();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (outputStream != null) {
try {
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public ArrayList exploredFolder(String sAbsolutePath) {
File[] sfiles;
File fsSelectedPath = new File(sAbsolutePath);
sfiles = fsSelectedPath.listFiles();
if (sfiles == null) {
return null;
}
for (int j = 0; j < sfiles.length; j++) {
File f = sfiles[j];
if (f.isDirectory() == true) {
exploredFolder(f.getAbsolutePath());
} else {
filesToAdd.add(f);
}
}
return filesToAdd;
}
public static void main(String[] args) {
new CreateZipWithOutputStreams().CreateZipWithOutputStreams("c:\\ZipTest");
}
}
谢谢!
好的,所以首先附加的代码应该可以正常工作,因为CreateZipWithOutputStreams()
exploredFolder(String absolutePath)
方法返回的是“要添加的文件”, CreateZipWithOutputStreams()
方法将使用该CreateZipWithOutputStreams()
来创建一个单独的layered(平面)的zip文件。
需要做的是循环遍历各个文件夹,并将其继续添加到ZipOutputStream
。
请通过下面的链接,您将找到代码片段和详细说明。
让我知道是否有帮助!
http://www.java-forums.org/blogs/java-io/973-how-work-zip-files-java.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.