【发布时间】:2021-08-25 00:48:08
【问题描述】:
我的任务是使用涉及的开源 'zip4jlibrary for creating and unzipping of password-protected zip files. Method parameters will bebyte[]of file content and password and it should return a byte array as output (unzipped or zipped content), noFile system`。我尝试了以下抛出的代码段
'net.lingala.zip4j.exception.ZipException:文件不存在:\test\Test.txt' 在行“zipFile.addFiles(filesToAdd, zipParameters);”我在这里缺少什么?
线程“主”net.lingala.zip4j.exception.ZipException 中的异常:文件不存在:\test\ZipThis.txt
在 net.lingala.zip4j.util.FileUtils.assertFileExists(FileUtils.java:526)
在 net.lingala.zip4j.util.FileUtils.assertFilesExist(FileUtils.java:359)
在 net.lingala.zip4j.tasks.AbstractAddFileToZipTask.addFilesToZip(AbstractAddFileToZipTask.java:62)
在 net.lingala.zip4j.tasks.AddFilesToZipTask.executeTask(AddFilesToZipTask.java:27)
在 net.lingala.zip4j.tasks.AddFilesToZipTask.executeTask(AddFilesToZipTask.java:15)
在 net.lingala.zip4j.tasks.AsyncZipTask.performTaskWithErrorHandling(AsyncZipTask.java:51)
在 net.lingala.zip4j.tasks.AsyncZipTask.execute(AsyncZipTask.java:45)
在 net.lingala.zip4j.ZipFile.addFiles(ZipFile.java:318)
在 net.lingala.zip4j.ZipFile.addFile(ZipFile.java:275)
public class ExtractZip {
public static byte[] extractWithZipInputStream(byte[] inputArr, char[] password) {
LocalFileHeader localFileHeader;
int readLen;
InputStream byteStream = new ByteArrayInputStream(inputArr);
byte[] readBuffer = new byte[4096];
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ZipInputStream zipInputStream = new ZipInputStream(byteStream, password);
try {
while ((localFileHeader = zipInputStream.getNextEntry()) != null) {
while ((readLen = zipInputStream.read(readBuffer)) != -1) {
bos.write(readBuffer, 0, readLen);
}
break;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bos.close();
} catch (Exception e) {
}
try {
zipInputStream.close();
} catch (Exception e) {
}
}
return bos.toByteArray();
}
public static void main(String[] args) {
FileOutputStream fos;
byte[] inputBuffer = new byte[1024];
try {
ZipParameters zipParameters = new ZipParameters();
zipParameters.setEncryptFiles(true);
zipParameters.setEncryptionMethod(EncryptionMethod.ZIP_STANDARD);
List<File> filesToAdd = Arrays.asList(new File("/test/ZipThis.txt"));
ZipFile zipFile = new ZipFile("/test/Template_Zip.zip", "abc123".toCharArray());
zipFile.addFiles(filesToAdd, zipParameters);
inputBuffer = Files.readAllBytes(Paths.get("/test/Template_Zip.zip"));
byte[] outputArr = ExtractZip.extractWithZipInputStream(inputBuffer, "abc123".toCharArray());
//Test if you can create a file using with this byte array
File unZipped = new File("/test/unzipped/temp");
fos = new FileOutputStream(unZipped);
fos.write(outputArr[0]);
fos.flush();
fos.close();
zipFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
【问题讨论】: