I want to access the most recent directory of windows file system using Java. The most recent folder will be generated in path D:\CorrectionsLanding
at runtime with random naming convention. Could somebody please let me know how to handle this?
I want to access the most recent directory of windows file system using Java. The most recent folder will be generated in path D:\CorrectionsLanding
at runtime with random naming convention. Could somebody please let me know how to handle this?
To run a search though the whole system you do something like this , it will find the most recently /modified/ directory - it works recursively
public static void main(String args[]) {
int i;
String dir="c:", tmp=null;
long time=0;
File tempDir, tempFile;
Vector fileQ=new Vector();
fileQ.add(dir);
while(!fileQ.isEmpty()) {
tempDir=new File((String)fileQ.remove(0));
if(tempDir.list()!=null)
for(i=0; i<tempDir.list().length; i++) {
tempFile=new File(tempDir.getPath()+File.separatorChar+tempDir.list()[i]);
if(tempFile.isDirectory()) {
System.out.println(tempFile.getPath()+" "+fileQ.size());
if(tempFile.lastModified()>time) { time=tempFile.lastModified(); tmp=tempFile.getPath(); }
fileQ.add(tempFile.getPath());
}
}
}
System.out.println("most recently modified "+tmp);
}
Here is my rendition of the task for getting the most recent directory created/modified from the Windows O/S File System. I'm not sure how it would work for other Operating Systems such as IOS or UNIX however since I don't have those systems to test it on :/
In any case... the code looks pretty long winded but then again there is a mile of comments within it which can be removed. The code is a runnable class utilizing the Scanner for User input to the output console (pane) in order to supply the directory to search in (ie: D:\CorrectionsLanding).
Again, as with just about anything in Java, several things can be done a dozen different ways but I feel that the way the code is presented here is relatively easy to follow and can be optimized as you see fit.
At the very least, I hope you find it amusing if not helpful to someone.
Here is the code (copy/paste/run):
import java.io.File;
import java.io.FilenameFilter;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.Locale;
import java.util.Scanner;
public class MostRecentDirectory {
// Set some output attributes to make things look
// kinda pertty :)
static String purple = "\u001B[35m", red = "\u001B[31m" , blue = "\u001B[34m";
static String bold = "\u001b[1m", reset = "\u001B[0m";
public static void main(String[] args) {
// Open the Scanner for User Input from output
// console (pane).
Scanner userInput = new Scanner(System.in);
System.out.println("Please enter the directory path we are to check,\n"
+ "or enter nothing to quit:");
String directoriesPath = userInput.nextLine();
//Quit if nothing was supplied.
if ("".equals(directoriesPath)) { System.exit(0); }
String recentFolder = getMostRecentDirectory(directoriesPath);
// Quit if there was an Exception (Error).
if ("".equals(recentFolder)) { System.exit(0); }
// Display what we found - Remember, The most recent directory
// and the date/time of creation is delimited with a Pipe (|)
// character when it's return from the getMostRecentDirectory()
// method...
//Parse out the folder name and the date/time from our returned
//delimited string into separate String variables.
String recFolder = recentFolder.substring(0, recentFolder.indexOf("|"));
String recFolderDate = recentFolder.substring(recentFolder.indexOf("|") + 1,
recentFolder.length());
//Display results.
System.out.println("\nChecked directories within: " + purple + directoriesPath + reset);
System.out.println("The first most recently created or modified directory is: " + bold + red +
recFolder + reset + "\nThe date and time it was created or "
+ "modified is : " + blue + recFolderDate);
System.out.println(red + "---->" + reset + " Process Complete " + red + "<----\n" + reset);
//Close Scanner input.
userInput.close();
}
private static String getMostRecentDirectory(String directoriesPath) {
// Create and initialize a file object pointing
// to our Directories.
File file = new File(directoriesPath);
// Make sure the supplied path exists...
if (!file.exists()) {
System.out.println( bold + red + "ERROR - The supplied Path Does Not Exist!" + reset);
return "";
}
// Fill the directories variable String Array with folders
// contained within the supplied path. This DOES NOT retrieve
// nested subfolders within the path.
String[] directories = file.list(new FilenameFilter() {
@Override
public boolean accept(File current, String name) {
return new File(current, name).isDirectory();
}
});
// Iterate through those found directories now and add
// their creation/last modified date to each element.
// This addition is delimited with the Pipe (|) character.
// This could actually be skipped but it's always nice to
// have all pertinent data in one array for other possible
// processing features. Well...IMHO anyway.
// Create a date format that's easier to work with since the
// lastModified() method uses some long winded date format :P
DateFormat dFormat = new SimpleDateFormat("MM/dd/yyyy hh:mm:ssa");
for (int i = 0; i < directories.length; i++) {
// Load the stored found directory into a file object
File f = new File(directoriesPath + "\\" + directories[i]);
//Get the created or lastmodified date.
Date d = new Date(f.lastModified());
// Add the related date for each directory element
// within the Array.
directories[i]+= "|" + dFormat.format(d);
}
// I think the easiest and fastest way to get the most
// recent date from a bunch of dates is by using the
// Collections.max() method but do this we need to place
// dates into a List. Yes...we could have done that in the
// previous 'for loop' but for 'clarity' were going to use
// another. There's a lot of things we could have done
// differently here. :p
//Declare and initialize our new List as Date type.
List<Date> dates = new ArrayList<>();
// We want to maintain our same date format we used earlier
// but this time for a Date object instead of a String object.
String dFmt = "MM/dd/yyyy hh:mm:ssa";
SimpleDateFormat formatter = new SimpleDateFormat(dFmt, Locale.ENGLISH);
for (int i = 0; i < directories.length; i++) {
// We need to use a try/catch here because we're parsing
// and we need to catch any thrown ParseException.
try {
// Pull out the date string from our current Array Element.
String dateStrg = directories[i].substring(directories[i].indexOf("|") + 1, directories[i].length());
// Convert the date string to a Date object Type.
Date d = formatter.parse(dateStrg);
// Add the Date object to our List.
dates.add(d);
} catch (ParseException ex) { System.out.println(red + ex.getMessage() + reset); }
}
// Let's get the most recent Date sing the
// Collections.max() method...
Date mostRecentDate = Collections.max(dates);
// Now that we have the most recent date let's
// convert it to a date String format we like for
// comparison in the 'for loop' below and to return
// to the User. Both the most recent date and the dates
// contained within our Array will be converted to this
// format for comparison in order to match it up with the
// related directory.
DateFormat targetFormat = new SimpleDateFormat("EEEE - MMMM dd, yyyy - hh:mm:ssa");
String mrd = targetFormat.format(mostRecentDate);
// Now let's compare it to the first date we encounter within
// our directories[] Array that matches the most recent date...
String mostRecentFolder = "";
String theRecentFolderDate = "";
for (int i = 0; i < directories.length; i++) {
// Yup.. we're parsing again so we need try/catch
try {
// Let's get the date string from the current
// Array element...
String datePart = directories[i].substring(directories[i].indexOf("|")
+ 1, directories[i].length());
// Convert it to a Date object to get our desired
// date string format.
Date dirDate = formatter.parse(datePart);
theRecentFolderDate = targetFormat.format(dirDate);
// Now we compare the current Array date string element
// with the most recent date.
if (theRecentFolderDate.equals(mrd)) {
// There's a match so let's grab the
// directory name.
mostRecentFolder = directories[i].substring(0,
directories[i].indexOf("|"));
// We've got our first match so let's get outta here.
break;
}
} catch (ParseException ex) { System.out.println(red + ex.getMessage() + reset); }
}
// Return our results...
return mostRecentFolder + "|" + theRecentFolderDate;
}
}