在java中解压后删除zip文件
如何在java中删除zip文件? file.delete 方法返回 false。为什么?
File file = new File("/mibook/"+mFilename+"/"+mZipname.toString());
boolean deleted = file.delete();
编辑:
规则“删除前目录应清空..”是否适用于 zip 文件?
我的文件解压代码
public void unzip() throws IOException {
FileInputStream fin=null;
ZipInputStream zin=null;
File file =null;
ZipEntry ze ;
FileOutputStream fout=null;
try{
System.out.println(_zipFile );
System.out.println(_location);
fin = new FileInputStream(_zipFile);
zin = new ZipInputStream(fin);
ze= null;
byte[] buffer = new byte[1024];
int length;
while ((ze = zin.getNextEntry()) != null) {
file = new File((_location +"/" + ze.getName()));
file.getParentFile().mkdirs();
fout= new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
zin.close();
}catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
finally {
fin.close();
zin.close();
fout.close();
}
}
How to delete a zip file in java? file.delete method returns false. Why?
File file = new File("/mibook/"+mFilename+"/"+mZipname.toString());
boolean deleted = file.delete();
edit:
Rule "Directory should empty before deletion.." does it apply for zip file?
My file unzipping code
public void unzip() throws IOException {
FileInputStream fin=null;
ZipInputStream zin=null;
File file =null;
ZipEntry ze ;
FileOutputStream fout=null;
try{
System.out.println(_zipFile );
System.out.println(_location);
fin = new FileInputStream(_zipFile);
zin = new ZipInputStream(fin);
ze= null;
byte[] buffer = new byte[1024];
int length;
while ((ze = zin.getNextEntry()) != null) {
file = new File((_location +"/" + ze.getName()));
file.getParentFile().mkdirs();
fout= new FileOutputStream(_location + ze.getName());
while ((length = zin.read(buffer))>0) {
fout.write(buffer, 0, length);
}
zin.closeEntry();
fout.close();
}
zin.close();
}catch(Exception e) {
Log.e("Decompress", "unzip", e);
}
finally {
fin.close();
zin.close();
fout.close();
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您必须确保关闭 ZipFile。
例如我有:
You have to make sure you close your ZipFile.
For example I had:
如果 file.delete() 返回 false,那么我的猜测是另一个进程打开了 zip 文件 - 或者甚至可能是您自己的进程。
file.exists()
返回什么?If
file.delete()
returns false, then my guess is that another process has the zip file open - or possibly even your own process.file.exists()
return?当尝试删除您创建的文件时,这种情况很常见。请务必
关闭
用于创建解压缩文件的FileWriter。如果您不知道在哪里关闭文件,最好的选择可能是调用 file.deleteOnExit() ,即使您不小心打开了一些文件句柄,它也应该会成功。
This is very common when attempting to delete a file that you've created. Be sure to
close
the FileWriter you used to create the unzipped file.If you can't figure out where to close the file, your best bet may be to call
file.deleteOnExit()
which should succeed even if you accidentally leave a few file handles open.使用:
FileUtils.delete(yourFile);
这纠正了我的问题
Use :
FileUtils.delete(yourFile);
This corrected my problem