繁体   English   中英

Windows中的Java:目录中具有特定名称的文件

[英]Java in Windows: files in a directory ordered with a specific name

我正在编写一个Java程序,该程序在执行过程中将创建一个使用以下格式命名的日志文件:

dateFormat = new SimpleDateFormat("HH_mm_ss_dd_MM_yy");

执行完程序后,我在一个特定的目录中获得了这样的文件:

14_10_02_17_07_19.log

因为该文件是在17/07/2019 14:10:02执行期间自动创建的。 执行完一些命令后,我将在此目录中包含一些文件,并且每个文件的名称显然都不同。 我需要以降序存储日志文件,从最近(第一个)到最早(最后一个)。

如何使用这种格式(“ HH_mm_ss_dd_MM_yy”)或类似的文件名来进行处理? 有没有一种方法,而无需手动修改目录属性并且不使用文件的最后修改日期?

Windows目录中的文件没有存储顺序。 Windows资源管理器默认情况下按字母顺序对文件进行排序。

确定按上次修改日期排序对您有用吗?

如果您的问题是如何在Java中以这种方式排序,则Arrays.sort()为您提供此功能。 例如, Arrays.sort(list, new WindowsExplorerStringComparator()); 将以与Windows资源管理器相同的方式对其进行排序。

但是,由于文件没有明确的顺序,因此无法以特殊的方式保存文件,以使Windows资源管理器始终按特定的顺序加载文件,而没有诸如在文件名上加前缀以强制执行特定操作之类的棘手解决方案字母顺序。

在特定操作系统的规则内,没有理由无法为您的日志文件命名。 也不能保证文件将以任何特定顺序保存在特定目录中。 您希望以可视方式查看文件的顺序取决于您的应用程序显示那些创建的文件。

对于以创建的升序或降序显示文件,我认为文件的创建(或最后修改)时间戳是排序依据的最佳替代方法,而不是文件名本身。 文件名中的时间戳仅提供对所需文件的快速引用,以查看哪个文件当然是有道理的,因此应该使用...但是...出于显示目的从最新文件到最旧文件或从最旧文件到最新文件的排序应该通过每个文件的时间戳来完成。 这也很有意义。

下面,我提供了一种方法( getFolderFilesInOrder() ),用于完全执行上述操作。 该方法通过创建(最后修改)时间戳按升序或降序对提供的目录(文件夹)中的文件进行排序。 默认情况下,该方法将以升序返回指定目录内所有文件的String []数组。 如果为sortOrderType参数提供1 ,则该方法将按降序返回指定目录内所有文件的String []数组。

这是getFolderFilesInOrder()方法(Java 8+):

/**
 * Returns a String[] Array of all the files within the supplied directory (folder) 
 * in either Ascending or Descending order. By default the full absolute path and 
 * the file name are returned, not just the file name.<br><br>
 * 
 * If you want the files list to be sorted in Descending Order the supply <b>1</b> 
 * within the optional <b>sortOrder</b> parameter.<br><br>
 * 
 * If you want just the file names within the String[] Array then supply <b>1</b> 
 * within the optional <b>fileNamesOnly</b> parameter.<br><br>
 * 
 * @param folderPath (String) The full path to the file system directory (folder) 
 * in which you want to get the list of files from.<br>
 * 
 * @param options (Optional - Integer):<pre>
 * 
 *      sortOrder       - Default is 0 (Ascending Order) which means the files
 *                        list will ne returned in ascending sort order. If any 
 *                        value other than 0 (ie: 1) is supplied then the files
 *                        list will be returned in descending order.
 * 
 *      fileNamesOnly   - Default is 0 where Path and file name are returned within
 *                        the String[] Array. If any value other than 0 (ie: 1) 
 *                        is supplied then only the file names itself will be 
 *                        returned within the String[] Array.
 *                     
 *                        If an argument is supplied to this optional parameter 
 *                        then something MUST also be supplied to the optional 
 *                        <b>sortOrder</b> parameter (either 0 or 1).</pre>
 * 
 * @return (One Dimensional String Array) The files contained within the supplied 
 * directory path in the desired sort order based on their Creation (or last modified) 
 * timestamp.
 */
public String[] getFolderFilesInOrder(String folderPath, int... options) {
    File folder = new File(folderPath);
    if (!folder.exists() && !folder.isDirectory()) {
        System.err.println("Either the supplied folder doesn't exist "
                         + "or it is not a directory!");
        return null;
    }
    int sortOrder = 0;      // Default - Ascending Order | any value other than 0 for Descending Order.
    int fileNamesOnly = 0;  // Default - Path & file name | any value other than 0 for file names only.
    if (options.length >= 1) {
        sortOrder = options[0];
        if (options.length >= 2) {
            fileNamesOnly = options[1];
        }
    }

    File[] folderFilesList = folder.listFiles();
    if (sortOrder == 0) {
        Arrays.sort(folderFilesList, Comparator.comparingLong(File::lastModified));
    } 
    else {
        Arrays.sort(folderFilesList, Comparator.comparingLong(File::lastModified).reversed());
    }

    List<String> filesList = new ArrayList<>();
    for (File f : folderFilesList) {
        if (f.isFile()) {
            filesList.add(fileNamesOnly == 0 ? f.getAbsolutePath() : f.getName());
        }
    }
    return filesList.toArray(new String[0]);
}

要使用此方法:

String folderPath = "C:\\My Log File\\AppLogs";
String[] logFiles = getFolderFilesInOrder(folderPath);
for (String s : logFiles) {
    System.out.println(s);
}

一个名为logFiles的String []数组将包含C:\\\\My Log File\\\\AppLogs目录中找到的所有日志文件( 带有路径 ),这些C:\\\\My Log File\\\\AppLogs基于文件时间戳以升序排列。


String[] logFiles = getFolderFilesInOrder(folderPath, 1);

一个名为logFiles的String []数组将包含在C:\\\\My Log File\\\\AppLogs目录中找到的所有日志文件( 带有路径 ),该C:\\\\My Log File\\\\AppLogs基于文件时间戳以降序排列。


String[] logFiles = getFolderFilesInOrder(folderPath, 0, 1);

一个名为logFiles的String []数组将包含在C:\\\\My Log File\\\\AppLogs目录中,根据文件时间戳升序排列的所有日志文件( 仅文件名 )。


String[] logFiles = getFolderFilesInOrder(folderPath, 1, 1);

一个名为logFiles的String []数组将包含基于文件时间戳降序C:\\\\My Log File\\\\AppLogs目录中找到的所有日志文件( 仅文件名 )。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM