Java 在文件夹中搜索索引

标签 java indexing webserver

我编写了一个小型网络服务器应用程序。现在我遇到了问题,我现在不知道如何显示索引文件。如何获取以index开头的目录中的第一个文件?无论哪个文件扩展名。我使用 new File("Path/To/Dir"); 获取目录。

请帮助我!

问候

最佳答案

您可以使用File#list()方法。

    // your directory in which you look for index* files
    File directory = new File(".");
    // note that indexFileNames may be null
    String[] indexFileNames = directory.list(new FilenameFilter() {
        public boolean accept(File dir, String name) {
            return name.startsWith("index");
        }
    });
    if (indexFileNames != null) {
        for (String name : indexFileNames) {
            System.out.println(name);
        }
    }

这将找到名称以 index 前缀开头的所有文件。

请注意,list() 方法返回文件和目录的名称。如果您只需要文件,则可以增强 FilenameFilter 逻辑。

要获取这些文件中的第一个,您需要定义一些顺序。例如,如果您需要按文件名称的字母顺序(区分大小写)对文件进行排序,您可以执行以下操作:

    if (indexFileNames != null) {
        // sorting the array first
        Arrays.sort(indexFileNames);
        // picking the first of them
        if (indexFileNames.length > 0) {
            String firstFileName = indexFileNames[0];
            // ... do something with it
        }
    }

如果您需要一些特殊订单,您还可以使用一些比较器进行排序:

Arrays.sort(indexFileNames, comparator);

另一种方法是避免排序并使用 Collections#min() 方法:

if (indexFileNames.length > 0) {
    String firstFileName = Collections.min(Arrays.asList(indexFileNames));
    // ... process it
}

Collections#min() 也有一个带有 Comparator 的版本。

关于Java 在文件夹中搜索索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44315979/

相关文章:

java - 如何在 Java 中使用单独的枚举类引用静态类?

java - 登录远程 Windows 服务器并执行 .bat 文件

java - 获取 java.lang.OutOfMemoryError : GC overhead limit exceeded while trying to reader a big excel file(. xlsx)

java - Web 应用程序中的一些字符串的翻译。

java - 如何在 - 和 ^ 之间或 - 之后获取字符串

sql - 哪些索引实现可以处理任意列组合?

hadoop - Druid 批量索引 inputSpec 类型粒度,错误为 "no input paths specified in job"

php - mysqli 中每行的唯一 ID

go - 如何在 golang 网络服务器中使用 prometheus 监控请求成本时间

java - Tomcat,httpd : Running both at same time and calling based upon URL.