How to get the last created (not last modified) folder name/path in a directory using JAVA? I could not find answers related to JAVA, hence posting here.
CodePudding user response:
It takes a few steps, for example:
- list all elements of a directory
- filter for directories
- get file creation time
- save up the path time combo in a list
- find the minimum of the list with respect of time
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.ArrayList;
import java.util.List;
public class LastCreatedDir {
record PathAndTime(Path path, FileTime time) { }
public static void main(String[] args) throws Exception {
Path path = Paths.get("..\\");
List<PathAndTime> list = new ArrayList<>();
// 1. -------------------------------------
try (var files = Files.list(path)) {
files.forEach(p -> {
// 2. -----------------------------
if (Files.isDirectory(p)) {
try {
// 3. -----------------------
BasicFileAttributes attr = Files.readAttributes(p,
BasicFileAttributes.class);
FileTime fileTime = attr.creationTime();
// 4. -----------------------
list.add(new PathAndTime(p, fileTime));
} catch (IOException ex) {
ex.printStackTrace();
}
}
});
}
// 5. -------------------------------------
var result = list.stream().min((a, b) -> {
return b.time.compareTo(a.time);
});
result.ifPresentOrElse(entry -> {
System.out.println(entry.path " @ " entry.time);
}, () -> {
System.out.println("No directories found");
});
}
}