获取目录的全名及其包含的字符串

Get Full Name of Directory with String It Contains

我正在尝试使用 Java 使用目录包含的字符串获取目录的全名。基本上,我的用例是我希望能够使用 Firefox 默认配置文件目录中的文件。所以我在 Windows 7 中的 Firefox 配置文件目录具有以下路径:

C:\Users\myUser\AppData\Roaming\Mozilla\Firefox\Profiles\s529v6bj.default

我想使用该目录中的 prefs.js 文件。但是,将我的代码移植到另一台机器上时,.default 之前的字符串可以是任何内容,并且 default 之后甚至可以有更多字符。我可以保证的一件事是 Profiles 中只有一个目录包含字符串 "default"。我希望目录以字符串形式返回,基本上类似于 ...

String ffProfileDir = System.getProperty("user.home")+"\AppData\Roaming\Mozilla\Firefox\Profiles\*.default*";

除了我知道当然只是在 .default 的两边加上一些星号是行不通的。有什么建议吗?

这应该可以满足您的需求。

public class DirectoryReader {
    public static void main(String[] args) {
        readDirectory();
    }

    public static void readDirectory() {
        String root = System.getProperty("user.home") + "\AppData\Roaming\Mozilla\Firefox\Profiles\";
        File file = traverseFolder(new File(root));
        String fileName = file.getName(); // if you want to get the directory name
    }

    public static File traverseFolder(File root) {
        if (root.isDirectory()) {
            File[] files = root.listFiles();
            if (root == null) {
                return null;
            }

            for (File f : files) {
                String fileName = f.getName();
                if (fileName.matches(".*default.*")) {
                    System.out.println(fileName);
                   return f;
               }
           }
        }

        return null;
    }
}