如何根据文件创建时间获取文件夹中最近的50个文件



我有一个包含数千个文件的文件夹。我计划根据创建的日期读取最近的50个文件,Java默认读取创建最旧的文件,比较每个文件需要很多时间,有没有更好的方法来做到这一点?

我有一个文件夹usrdocumentsarchive,里面有1000个文件根据文件创建,要读取文件夹中的50个文档

您可以使用以下命令获取创建或最后修改时间

BasicFileAttributes attr = Files.readAttributes(path, BasicFileAttributes.class);
FileTime fileTime = attr.creationTime();

FileTime creationTime = (FileTime) Files.getAttribute(path, "creationTime");

现在,由于您可以获取创建时间(或上次修改时间),因此您可以根据创建时间对文件进行排序。

警告:迭代每个文件/目录将花费时间,但这取决于您的用例。我会这样做,如果任务是在后台运行,但不是为用户正在等待的操作。我将使用缓存来定期处理和存储面向用户的操作的结果。

下面的方法读取指定目录(文件夹)路径中的所有文件,并根据创建(或修改)时间戳按升序或降序对文件进行排序。String[] Array返回文件名或路径和文件名,具体取决于方法可选(varArg)参数中提供的内容。

/**
* 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.
* <p>
* If you want the files list to be sorted in Descending Order the supply
* <b>1</b> within the optional <b>sortOrder</b> parameter.
* <p>
* If you want just the file names within the String[] Array then supply
* <b>1</b>
* within the optional <b>fileNamesOnly</b> parameter.
* <p>
* <b>Example Usage:</b><pre>
*  {@code     String folderPath = "C:\Log Files\SpecificAppLogsFolder";
*       String[] logFiles = getFolderFilesInOrder(folderPath);
*       for (String s : logFiles) {
*           System.out.println(s);
*       }
*   }</pre>
*
* @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 - int):<pre>
*
*      sortOrder       - Default is 0 (Ascending Order) which means the files
*                        list will ne returned in ascending sort order (from 
*                        the oldest files to the newest files). If any
*                        value other than 0 (ie: 1) is supplied then the files
*                        list will be returned in descending order (from newest
*                        files to oldest files).
*
*      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 (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]);
}

你可以这样使用这个方法:

/* Get all files (file names only) within the supplied directory path 
(no sub-directories are processed) and sort them in descending order 
(newest to oldest) based on creation (modification) timestamp and 
return them in a String[] Array.                         */
String[] allFiles = getFolderFilesInOrder("C:/MyLogFilesDirectory", 1, 1);

// The number of files desired from the directory:
int numberOfFilesDesired = 50;

/* Just in case (for some reason) the supplied directory path
does not contain the desired number of files.       */
numberOfFilesDesired = Math.min(numberOfFilesDesired, allFiles.length);

// Retrieve the number of files we want.
String[] desiredFiles = new String[numberOfFilesDesired];
for (int i = 0; i < numberOfFilesDesired; i++) {
desiredFiles[i] = allFiles[i];

//You can omit the line below. It's just for demo purposes:
System.out.println((i+1) + ") " + desiredFiles[i]);
}

最新更新