递归文件搜索指定扩展名

时间:2018-12-26 18:58:25

标签: java recursion smb smbj

我正在使用SMBClient通过Java连接到我的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);
    }
}

1 个答案:

答案 0 :(得分:0)

这是对代码的一些相当简单的调整,以使其递归地填充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("..");
}