zip文件夹及其子文件夹中的文件列表 [英] List of files inside a zip folder and its subfolder
问题描述
我正在寻找一种方法来获取zip文件中的文件列表。我创建了一个方法来获取目录中的文件列表,但我也在寻找一种方法来获取zip文件,而不是只显示zip文件。
I am looking a way to get the list of files inside a zip file. I created a method to get the list of files inside a directory but I am also looking a way to get files inside a zip as well instead of showing just zip file.
这是我的方法:
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开始)以更通用的方式执行相同的操作。
After having searched for a better answer for a while, I finally found a better way to do this. You can actually do the same thing in a more generic way using the Java NIO API (Since 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中,或任何其他包含在内。
This approach has the advantage that you can travers ANY file system this way: your normal windows or Unix filesystem, the file system contain contained within a zip or a jar, or any other really.
然后,您可以轻松读取任何 Path <的内容/ code>通过
, Files
类,使用 Files.copy()
,<$ c $等方法c> File.readAllLines() File.readAllBytes()
等...
You can then trivially read the contents of any Path
via the Files
class, using methods like Files.copy()
, File.readAllLines()
, File.readAllBytes()
, etc...
这篇关于zip文件夹及其子文件夹中的文件列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!