1

我正在使用SMBClientJava 连接到我的 SMB 服务器。

如何递归扫描我的整个 SMB 共享以获取所有扩展名为 .mp4 的文件的列表?

这是我只扫描一个指定目录的代码:

private void btnFileCountActionPerformed(java.awt.event.ActionEvent evt) {
    SMBClient client = new SMBClient();
    try (Connection connection = client.connect("192.168.X.XXX")) {
        AuthenticationContext ac = new AuthenticationContext("XXXXXXX@hotmail.com", "XXXXXX".toCharArray(), "Mastafin");
        Session session = connection.authenticate(ac);

        try (DiskShare share = (DiskShare) session.connectShare("Folder With Spaces")) {
            for (FileIdBothDirectoryInformation f : share.list("LOTS OF SUBDIRS TO SCAN", "*.mp4")) {
                System.out.println("File : " + f.getFileName());
            }
        } catch (Exception e) {
            System.out.println(e);
        }
    } catch (Exception e) {
        System.out.println(e);
    }
}
4

1 回答 1

3

以下是对您的代码的一些相当简单的调整,以使其以ArrayList递归方式填充。这不一定是最有效的方法,因为它收集所有文件名,然后丢弃不.mp4以 .

private void btnFileCountActionPerformed(java.awt.event.ActionEvent evt) {
    try (SMBClient client = new SMBClient()) {
        try (Connection connection = client.connect(SERVER)) {
            AuthenticationContext ac = new AuthenticationContext(USERNAME, PASSWORD.toCharArray(), WORKGROUP);
            try (Session session = connection.authenticate(ac)) {
                try (DiskShare share = (DiskShare) session.connectShare(SHARE)) {
                    List<String> files = new ArrayList<>();
                    listFiles(share, START_DIR, files);
                    files.removeIf(name -> !name.toLowerCase().endsWith(".mp4"));
                    files.forEach(System.out::println);
                }
            }
        }
    } catch (IOException e) {
        e.printStackTrace(System.err);
    }
}

private void listFiles(DiskShare share, String path, Collection<String> files) {
    List<String> dirs = new ArrayList<>();
    String extPath = path.isEmpty() ? path : path + "\\";
    for (FileIdBothDirectoryInformation f : share.list(path)) {
        if ((f.getFileAttributes() & FileAttributes.FILE_ATTRIBUTE_DIRECTORY.getValue()) != 0) {
            if (!isSpecialDir(f.getFileName())) {
                dirs.add(f.getFileName());
            }
        } else {
            files.add(extPath + f.getFileName());
        }
    }
    dirs.forEach(dir -> listFiles(share, extPath + dir, files));
}

private static boolean isSpecialDir(String fileName) {
    return fileName.equals(".") || fileName.equals("..");
}
于 2018-12-31T17:15:29.570 回答