我希望在 Java 中创建一个 zip 程序,其中的 zip 文件和文件夹可以说是这样的结构 -
- 文件夹一/
- 文件夹一/one.txt
- 文件夹一/二.mp3
- 文件夹一/三.jpg
- 文件夹二/
- 文件夹二/四.doc
- 文件夹二/五.rtf
- 文件夹二/文件夹三/
- 文件夹二/文件夹三/six.txt
我使用了 zip4j 开源,我在一个列表中收集了所有文件(带有绝对路径),然后将其提供给 zip,但它仅在 my.zip 中压缩文件 -
- 一个.txt
- 二.mp3
- 三.jpg
- 四.doc
- 五.rtf
- 六.txt
如何在压缩和解压缩时保留与之前在本地相同的结构。请建议是否有任何其他开源可以帮助我像其他 Windows zip 程序一样在相同结构的文件和文件夹中压缩/解压缩。
代码如下——
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");
}
}
谢谢!