[英]FileNotFoundException when trying to unzip an archive with java.util.zip.ZipFile
I have a silly problem i haven't been able to figure out. 我有一个愚蠢的问题,我一直无法弄清楚。 Can anyone help me?
谁能帮我? My Code is as:
我的代码是:
String zipname = "C:/1100.zip";
String output = "C:/1100";
BufferedInputStream bis = null;
BufferedOutputStream bos = null;
try {
ZipFile zipFile = new ZipFile(zipname);
Enumeration<?> enumeration = zipFile.entries();
while (enumeration.hasMoreElements()) {
ZipEntry zipEntry = (ZipEntry) enumeration.nextElement();
System.out.println("Unzipping: " + zipEntry.getName());
bis = new BufferedInputStream(zipFile.getInputStream(zipEntry));
int size;
byte[] buffer = new byte[2048];
It doesn't create a folder but debugging shows all the contents being generated. 它不会创建文件夹,但是调试会显示所有正在生成的内容。 In Order to create a folder i used the code
为了创建一个文件夹,我使用了代码
if(!output.exists()){ output.mkdir();} // here i get an error saying filenotfoundexception
bos = new BufferedOutputStream(new FileOutputStream(new File(outPut)));
while ((size = bis.read(buffer)) != -1) {
bos.write(buffer, 0, size);
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
bos.flush();
bos.close();
bis.close();
}
My zip file contains images: a.jpg b.jpg... and in the same hierarchy, I have abc.xml. 我的zip文件包含图像:a.jpg b.jpg ...,在同一层次结构中,我有abc.xml。 I need to extract the content as is in the zip file.
我需要提取压缩文件中的内容。 Any helps here.
任何帮助在这里。
There are a few problems with your code: Where is outPut declared? 您的代码有一些问题:outPut在哪里声明?
output
is not a file but a string, so exists()
and mkdir()
do not exist. output
不是文件而是字符串,因此exist exists()
和mkdir()
不存在。 Start by declaring output
like: 首先声明如下
output
:
File output = new File("C:/1100");
Furthermore, outPut
(with big P) is not declared. 此外,未声明
outPut
(具有大P)。 It be something like output + File.seprator + zipEntry.getName()
. 它类似于
output + File.seprator + zipEntry.getName()
。
bos = new BufferedOutputStream(new FileOutputStream(output + File.seprator + zipEntry.getName()));
Note that you don't need to pass a File to FileOutputStream, as constructors show in the documentation . 请注意,您不需要将文件传递到FileOutputStream,如文档中的构造函数所示。
At this point, your code should work if your Zip file does not contain directory. 此时,如果您的Zip文件不包含目录,则您的代码应该可以使用。 However, when opening the output stream, if zipEntry.getName() has a directory component (for instance
somedir/filename.txt
), opening the stream will result in a FileNotFoundException
, as the parent directory of the file you try to create does not exist. 但是,在打开输出流时,如果zipEntry.getName()具有目录组件(例如
somedir/filename.txt
),则打开流将导致FileNotFoundException
,因为您尝试创建的文件的父目录不会存在。 If you want to be able to handle such zip files, you will find your answer in: How to unzip files recursively in Java? 如果您希望能够处理此类zip文件,则可以在以下位置找到答案: 如何在Java中递归解压缩文件?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.