我收到了一个 zip 扩展名的压缩文件。我无法使用 Windows 资源管理器直接打开它。我可以使用 7Zip 提取它,它会引发一些错误,但文件仍按预期解压缩。我可以使用winrar解压,没有错误,文件按预期解压。
然后我尝试使用 java.util.unzip / zip4j 解压缩。
java.util.zip 代码:
public static void unzip(String zipFilePath,
String destDirectory) throws IOException {
File destDir = new File(destDirectory);
if (!destDir.exists()) {
destDir.mkdir();
}
ZipInputStream zipIn =
new ZipInputStream(new FileInputStream(zipFilePath));
ZipEntry entry = zipIn.getNextEntry();
// iterates over entries in the zip file
while (entry != null) {
String filePath = destDirectory + File.separator + entry.getName();
if (!entry.isDirectory()) {
// if the entry is a file, extracts it
extractFile(zipIn, filePath);
} else {
// if the entry is a directory, make the directory
File dir = new File(filePath);
dir.mkdir();
}
zipIn.closeEntry();
entry = zipIn.getNextEntry();
}
zipIn.close();
}
/**
* Extracts a zip entry (file entry)
* @param zipIn
* @param filePath
* @throws IOException
*/
private static void extractFile(ZipInputStream zipIn,
String filePath) throws IOException {
BufferedOutputStream bos =
new BufferedOutputStream(new FileOutputStream(filePath));
byte[] bytesIn = new byte[BUFFER_SIZE];
int read = 0;
while ((read = zipIn.read(bytesIn)) != -1) {
bos.write(bytesIn, 0, read);
}
bos.close();
}
使用上面的代码,没有错误发生,但我得到一个空文件夹。
zip4j 代码:
String zipFilePath = "C:\\Juw\\JR\\file\\output\\020030214112016.zip";
//String zipFilePath = "C:\\Juw\\JR\\file\\output\\myFile.zip";
String destDirectory = "C:\\Juw\\JR\\file\\output\\targetUnzip";
try {
ZipFile zipFile = new ZipFile(zipFilePath);
zipFile.extractAll(destDirectory);
} catch (Exception ex) {
ex.printStackTrace();
}
并且有一个例外:net.lingala.zip4j.exception.ZipException: zip headers not found。可能不是 zip 文件
如果我尝试使用 winrar 解压缩文件,然后我使用 Windows 内置的 zip 功能对其进行压缩。我可以使用我的代码成功解压缩它。我的尺寸和客户给我的尺寸不同。我的是508kb,另一个是649kb。
问题是: - 是否有任何使用 / 作为强大的 winrar 的 java 库,可以无错误地提取压缩文件?- 解决这种情况的最佳做法是什么?
提前谢谢了 :)