Home > Software engineering >  JAVA - How to get last/recently CREATED folder name in a directory?
JAVA - How to get last/recently CREATED folder name in a directory?

Time:06-15

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:

  1. list all elements of a directory
  2. filter for directories
  3. get file creation time
  4. save up the path time combo in a list
  5. 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");
        });
    }
}
  •  Tags:  
  • java
  • Related