这里我有文件夹(ZipFilesFolder),它由 10 个 zip 文件组成,例如 one.zip、two.zip、三.zip..ten.zip,我每次都会将文件从该文件夹传递到 zipFileToUnzip 作为 zipFilename .我需要将结果放在同一个文件夹(ZipFilesFolder)中,我需要解压缩这些文件,而不是一个.zip,两个.zip,..一个,两个,三个文件夹必须可见。
public static void zipFileToUnzip(File zipFilename) throws IOException {
try {
//String destinationname = "D:\\XYZ";
byte[] buf = new byte[1024];
ZipInputStream zipinputstream = null;
ZipEntry zipentry;
zipinputstream = new ZipInputStream(new FileInputStream(zipFilename));
zipentry = zipinputstream.getNextEntry();
while (zipentry != null) {
//for each entry to be extracted
String entryName = zipentry.getName();
System.out.println("entryname " + entryName);
int n;
FileOutputStream fileoutputstream;
File newFile = new File(entryName);
String directory = newFile.getParent();
if (directory == null) {
if (newFile.isDirectory()) {
break;
}
}
fileoutputstream = new FileOutputStream(
destinationname + entryName);
while ((n = zipinputstream.read(buf, 0, 1024)) > -1) {
fileoutputstream.write(buf, 0, n);
}
fileoutputstream.close();
zipinputstream.closeEntry();
zipentry = zipinputstream.getNextEntry();
}//while
zipinputstream.close();
} catch (IOException e) {
}
}
这是我的代码,但它不起作用,有人可以帮助我,如何获得所需的输出。
最佳答案
您的代码存在一些问题:
- 它无法编译,因为
destinationname
已被注释,但在打开FileOutputStream
时被引用 IOException
被捕获并忽略。如果您抛出它们,您会收到错误消息,可以帮助您诊断问题- 打开
FileOutputStream
时,您只需连接两个字符串,而无需在其间添加路径分隔符。 - 如果要创建的文件位于目录中,则不会创建该目录,因此
FileOutputStream
无法创建该文件。 - 发生异常时流不会关闭。
如果您不介意使用 guava ,这简化了将流复制到文件的过程,您可以使用以下代码:
public static void unzipFile(File zipFile) throws IOException {
File destDir = new File(zipFile.getParentFile(), Files.getNameWithoutExtension(zipFile.getName()));
try(ZipInputStream zipStream = new ZipInputStream(new FileInputStream(zipFile))) {
ZipEntry zipEntry = zipStream.getNextEntry();
if(zipEntry == null) throw new IOException("Empty or no zip-file");
while(zipEntry != null) {
File destination = new File(destDir, zipEntry.getName());
if(zipEntry.isDirectory()) {
destination.mkdirs();
} else {
destination.getParentFile().mkdirs();
Files.asByteSink(destination).writeFrom(zipStream);
}
zipEntry = zipStream.getNextEntry();
}
}
}
关于java - zip 文件未解压缩在同一文件夹中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23950954/