我正在寻找一种方法来获取 zip 文件内的文件列表。我创建了一种方法来获取目录中的文件列表,但我也在寻找一种方法来获取 zip 中的文件,而不是仅显示 zip 文件。
这是我的方法:
public ArrayList<String> listFiles(File f, String min, String max) {
try {
// parse input strings into date format
Date minDate = sdf.parse(min);
Date maxDate = sdf.parse(max);
//
File[] list = f.listFiles();
for (File file : list) {
double bytes = file.length();
double kilobytes = (bytes / 1024);
if (file.isFile()) {
String fileDateString = sdf.format(file.lastModified());
Date fileDate = sdf.parse(fileDateString);
if (fileDate.after(minDate) && fileDate.before(maxDate)) {
lss.add("'" + file.getAbsolutePath() +
"'" + " Size KB:" + kilobytes + " Last Modified: " +
sdf.format(file.lastModified()));
}
} else if (file.isDirectory()) {
listFiles(file.getAbsoluteFile(), min, max);
}
}
} catch (Exception e) {
e.getMessage();
}
return lss;
}
在寻找更好的答案一段时间后,我终于找到了更好的方法来做到这一点。实际上,您可以使用 Java NIO API(自 Java 7 起)以更通用的方式执行相同的操作。
// this is the URI of the Zip file itself
URI zipUri = ...;
FileSystem zipFs = FileSystems.newFileSystem(zipUri, Collections.emptyMap());
// The path within the zip file you want to start from
Path root = zipFs.getPath("/");
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path path, BasicFileAttributes attrs) throws IOException {
// You can do anything you want with the path here
System.out.println(path);
// the BasicFileAttributes object has lots of useful meta data
// like file size, last modified date, etc...
return FileVisitResult.CONTINUE;
}
// The FileVisitor interface has more methods that
// are useful for handling directories.
});
这种方法的优点是您可以通过这种方式遍历任何文件系统:您的普通 Windows 或 Unix 文件系统、zip 或 jar 或任何其他文件系统中包含的文件系统。
然后您可以轻松阅读任何内容Path
通过Files
类,使用类似的方法Files.copy()
, File.readAllLines()
, File.readAllBytes()
, etc...
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)