Get Latest File and Folder using Java

Sometimes we need to find the latest file/ folder. I usually use this piece of code to select the latest report or screengrab for emailing after the test run. Here, I will give the complete code including creation of the folder to use for retrieval.

This is the sample code to create multi-level folders in the root directory as defined by the user:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class createNewFileFolder {

public static void main(String[] args) {
 
 mkSingleDir(<Path to Dir>,<Dir Name>);
 mkMultipleDir(<Path to Dir/Dir1/Dir2/Dir3>);     
 String file = new SimpleDateFormat("yyyy-MM-dd_hh-mm-ss'.xls'").format(new Date());
 System.out.println(file);
}

public static void mkSingleDir(String dirPath, String dirName){

    File file = new File(dirPath+dirName);
    if (!file.exists()) {
        if (file.mkdir()) {
            System.out.println("Directory is created: "+file);
        } else {
            System.out.println("Failed to create directory!");
        }
    }else{
     System.out.println("Directory exists: "+file); 
    }  
}

public static void mkMultipleDir(String dirPath){
 // Eg.: "C:\\Directory2\\Sub2\\Sub-Sub2"
 File files = new File(dirPath); 
    if (!files.exists()) {
        if (files.mkdirs()) {
            System.out.println("Multiple directories are created!");
        } else {
            System.out.println("Failed to create multiple directories!");
        }
    }else{
     System.out.println("Directory exists: "+files); 
    }
}
}


This method reads the latest file in the folder defined by the user:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
private static void printLatestFile_SingleLevel(Path root) throws IOException{

 System.out.println("List the most recent file in user defined folder");
 // Find all direct directories inside root as defined by the user
 Files.find(root, 1, (path, attrs) -> attrs.isDirectory())
 // Check if latest is a directory or file
 .filter(p -> !p.equals(root))
 .forEach((dir) -> {
  try {
   // Find all contained files in any Folder
   Optional<Path> recentFile = Files.find(dir, Integer.MAX_VALUE, 
     (path, attrs) -> attrs.isRegularFile())
     // return the last modified file based on time
     .max((p1, p2)
       -> Long.compare(p1.toFile().lastModified(),
         p2.toFile().lastModified()));
   // If the file is present
   if (recentFile.isPresent()) {
    // Print modification time and file path and name
    printFileInfo(recentFile.get().toFile());
   }
  } catch (IOException ex) {
   ex.printStackTrace(System.err);
  }
 });
}


This method reads the latest file in the folder defined by the user:


 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
private static void printLatestFile_MultiLevel(Path root) throws IOException{
 System.out.println("List of the most recent file per each Directory");
 // Search all directories inside the root described by the user
 Files.find(root, Integer.MAX_VALUE, (path, attrs) -> attrs.isDirectory())
 // For each directory go further in - recursive call
 .forEach((dir) -> {
  try {
   // Find all contained files
   Optional<Path> recentFile = Files.find(dir, 1, 
    (path, attrs) -> attrs.isRegularFile())
    // Return the last modified file based on time
    .max((p1, p2)
     -> Long.compare(
      p1.toFile().lastModified(),
      p2.toFile().lastModified()));
   // If the file is present
   if (recentFile.isPresent()) {
    // Print modification time and file path and name
    printFileInfo(recentFile.get().toFile());
   }
  } catch (IOException ex) {
   ex.printStackTrace(System.err);
  }
 });
}


And this is how you can call all the above methods:


1
2
3
4
5
6
public static void main(String[] args) throws IOException  {
 Path root = Paths.get("/newbiesHelper/sampleFolder_Main");
 createFile(root);
 printLatestFile_SingleLevel(root);
 printLatestFile_MultiLevel(root);
}


This is the print method used in the methods above:


1
2
3
4
5
6
private static void printFileInfo(File file) {
 System.out.printf("  mtime: %td.%<tm.%<tY  %<tH:%<tM:%<tS  file: %s%n",
  new Date(file.lastModified()),
  file.getAbsolutePath()
  );
}



No comments:

Post a Comment