Best way to list files in Java, sorted by Date Modified?
I think your solution is the only sensible way. The only way to get the list of files is to use File.listFiles() and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a Comparator that uses File.lastModified() and pass this, along with the array of files, to Arrays.sort().
How to sort files list by date?
You can use the file.info
function to obtain details on your files. Once you have those details, you can sort the files accordingly. For example,
details = file.info(list.files(pattern="*.csv"))
gives a data frame containing, inter alia, modification and creation times. You can sort that data frame however you want. Here I sort according to modification time, mtime
:
details = details[with(details, order(as.POSIXct(mtime))), ]
files = rownames(details)
How do I sort results of File.listFiles() by creation date?
you can use Collections.sort or Arrays.sort or List.sort
You can get the creation date of a file by using java nio Files. readAttributes()
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(final File o1, final File o2) {
try {
BasicFileAttributes f1Attr = Files.readAttributes(Paths.get(f1.toURI()), BasicFileAttributes.class);
BasicFileAttributes f2Attr = Files.readAttributes(Paths.get(f2.toURI()), BasicFileAttributes.class);
return f1Attr.creationTime().compareTo(f2Attr.creationTime());
} catch (IOException e) {
return 0;
}
}
});
Or using Comparator.comparing:
Comparator<File> comparator = Comparator.comparing(file -> {
try {
return Files.readAttributes(Paths.get(file.toURI()), BasicFileAttributes.class).creationTime();
} catch (IOException e) {
return null;
}
});
Arrays.sort(files, comparator);
How do you get a directory listing sorted by creation date in python?
Update: to sort dirpath
's entries by modification date in Python 3:
import os
from pathlib import Path
paths = sorted(Path(dirpath).iterdir(), key=os.path.getmtime)
(put @Pygirl's answer here for greater visibility)
If you already have a list of filenames files
, then to sort it inplace by creation time on Windows (make sure that list contains absolute path):
files.sort(key=os.path.getctime)
The list of files you could get, for example, using glob
as shown in @Jay's answer.
old answer
Here's a more verbose version of @Greg Hewgill
's answer. It is the most conforming to the question requirements. It makes a distinction between creation and modification dates (at least on Windows).
#!/usr/bin/env python
from stat import S_ISREG, ST_CTIME, ST_MODE
import os, sys, time
# path to the directory (relative or absolute)
dirpath = sys.argv[1] if len(sys.argv) == 2 else r'.'
# get all entries in the directory w/ stats
entries = (os.path.join(dirpath, fn) for fn in os.listdir(dirpath))
entries = ((os.stat(path), path) for path in entries)
# leave only regular files, insert creation date
entries = ((stat[ST_CTIME], path)
for stat, path in entries if S_ISREG(stat[ST_MODE]))
#NOTE: on Windows `ST_CTIME` is a creation date
# but on Unix it could be something else
#NOTE: use `ST_MTIME` to sort by a modification date
for cdate, path in sorted(entries):
print time.ctime(cdate), os.path.basename(path)
Example:
$ python stat_creation_date.py
Thu Feb 11 13:31:07 2009 stat_creation_date.py
How to sort files from a directory by date in java?
Java 8
public static void sortOldestFilesFirst(File[] files) {
Arrays.sort(files, Comparator.comparingLong(File::lastModified));
}
public static void sortNewestFilesFirst(File[] files) {
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
}
Java 7
public static void sortOldestFilesFirst(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File a, File b) {
return Long.compare(a.lastModified(), b.lastModified());
}
});
}
public static void sortNewestFilesFirst(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File a, File b) {
return Long.compare(b.lastModified(), a.lastModified());
}
});
}
Sort list of files based on creation date in Python
The reason why it says it doesn't show up as a file when you try to use just os.path.getmtime
is because you're checking just path
, when you also have a directory: pathIn
.
You can either use join
when sorting:
files.sort(key=lambda f: os.path.getmtime(join(pathIn, f)))
Or, (and the syntax depends on your version of Python) you can directly store the full file path initially:
files = [fullPath for path in os.listdir(pathIn) if isfile((fullPath := join(pathIn, f)))]
This alleviates the need for filename=pathIn + "\\" + files[i]
later on in your code.
sorting files based on its creation date in android
I want list of file based on my creation date.
As the two previous answers pointed out, you can sort the files according to the modification date:
file.lastModified()
But the modification date is updated e.g. in the instant of renaming a file. So, this won't work to represent the creation date.
Unfortunately, the creation date is not available, thus you need to rethink your basic strategy:
see an old answer of CommonsWare
Sort file list by date
You could use PHP's glob function and a custom sorting function like this:
<?php
$sub = ($_GET['dir']);
$path = 'groundfish-meetings/';
$path = $path . "$sub";
$file_list = glob($path."*.pdf");
function sort_by_mtime($file1,$file2) {
$time1 = filemtime($file1);
$time2 = filemtime($file2);
if ($time1 == $time2) {
return 0;
}
return ($time1 < $time2) ? 1 : -1;
}
usort($file_list ,"sort_by_mtime");
$i = 1;
foreach($file_list as $file)
{
echo "$i. <option value='" . home_url('/groundfish-meetings/' . $file) .
"'>$file</option>";
$i++;
}
Related Topics
How to Remove Rows with All Zeros Without Using Rowsums in R
Aggregate by Specific Year in R
Assign Headers Based on Existing Row in Dataframe in R
Create Top-To-Bottom Fade/Gradient Geom_Density in Ggplot2
Convert Data Frame into Vector
Shiny Doesn't Show Me the Entire Selectinput When I Have Choices > 1000
Bookmarking and Saving the Bookmarks in R Shiny
R: Replace All Values in a Dataframe Lower Than a Threshold with Na
Aggregation Using Ffdfdply Function in R
How to Calculate the Average of a Variable Between Two Date Ranges Using a Loop or Apply Function
Dplyr::Select One Column and Output as Vector
Hyperlinking Text in a Ggplot2 Visualization
R Graphs: Creating Tufte's Horizontal Bar Lines