zip 文件夹及其子文件夹中的文件列表

use*_*607 -1 java io zip file

我正在寻找一种方法来获取 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;
}
Run Code Online (Sandbox Code Playgroud)

Lor*_*igs 5

在搜索了一段时间更好的答案后,我终于找到了一个更好的方法来做到这一点。实际上,您可以使用 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.
});
Run Code Online (Sandbox Code Playgroud)

这种方法的优点是您可以通过这种方式遍历任何文件系统:您的普通 Windows 或 Unix 文件系统、包含在 zip 或 jar 中的文件系统,或任何其他文件系统。

然后,您可以读出平凡中的任意内容Path通过Files类,使用类似的方法Files.copy()File.readAllLines()File.readAllBytes(),等...