我有用于解压缩zip文件内容的代码(如果必须创建目录,那么也会创建该目录)。
但是我想检查以下内容-
(1)从zip解压缩文件时,请检查文件是否已存在,并根据用户在运行时指定的值来覆盖该文件或保留原始文件。
具体来说,指定行下方的代码行应该是什么,该行检查该位置是否已经存在具有特定名称的文件?
下面单独给出应进行此检查(文件是否存在)的代码行...
copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(entry.getName())));
(2)如何检查指定名称的目录是否已经存在。在以下代码之前需要进行此检查-
(new File(entry.getName())).mkdir();
程序的完整代码如下:
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class Unzip {
public static final void copyInputStream(InputStream in, OutputStream out)
throws IOException
{
byte[] buffer = new byte[1024];
int len;
while((len = in.read(buffer)) >= 0)
out.write(buffer, 0, len);
in.close();
out.close();
}
public static final void main(String[] args) {
Enumeration entries;
ZipFile zipFile;
if(args.length != 1) {
System.err.println("Usage: Unzip zipfile");
return;
}
try {
zipFile = new ZipFile(args[0]);
entries = zipFile.entries();
while(entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry)entries.nextElement();
if(entry.isDirectory()) {
// Assume directories are stored parents first then children.
System.err.println("Extracting directory: " + entry.getName());
// This is not robust, just for demonstration purposes.
(new File(entry.getName())).mkdir();
continue;
}
System.err.println("Extracting file: " + entry.getName());
copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(entry.getName())));
}
zipFile.close();
} catch (IOException ioe) {
System.err.println("Unhandled exception:");
ioe.printStackTrace();
return;
}
}
}
最佳答案
您将需要使用java.io.File
检查文件夹或目录是否存在,如下所示:
// first obtain the base path where you are running your code
URL url = getClass().getClassLoader().getResource(".");
// then check for the existence of the file you need
File f = new File(url.getPath() + entry.getName());
// check for the flag to overwrite the file or it doesn't exist
if(!file.exists() || overwrite) {
copyInputStream(zipFile.getInputStream(entry),
new BufferedOutputStream(new FileOutputStream(entry.getName())));
}
可以使用相同的方法来检查文件夹是否存在。