2017-06-01 139 views
0

我已经写了一个小型的Web服务器应用程序。现在我有这个问题,我现在不怎么显示索引文件。我怎样才能得到以索引开头的目录中的第一个文件?不管是哪个文件扩展名。我得到new File("Path/To/Dir");的目录。文件夹中的Java搜索索引

请帮帮我!

问候

回答

2

你可以使用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逻辑。

要获得这些文件的第一个,您需要定义一些顺序。例如,如果您需要在alfabetically他们的名字文件(区分大小写的方式)进行排序,你可以做到以下几点:

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版本。

+0

我怎么能得到他们的第一个? – Markus

+0

我已经更新了答案,并提供了关于选择“第一个”元素的附加信息 –