简体   繁体   English

如何使用Java访问最新目录(不是文件)

[英]How to access most recent directory(not file) using Java

I want to access the most recent directory of windows file system using Java. 我想使用Java访问Windows文件系统的最新目录。 The most recent folder will be generated in path D:\\CorrectionsLanding 最新文件夹将在路径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 要通过整个系统执行搜索,您需要执行以下操作,它将找到最新的/ modified /目录-它以递归方式工作

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. 这是我对从Windows O / S文件系统中创建/修改的最新目录的任务的解释。 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 :/ 我不确定它如何在其他操作系统(例如IOS或UNIX)上运行,因为我没有那些系统可以在:/上对其进行测试

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). 该代码是一个可运行的类,利用“扫描仪用户”输入到输出控制台(窗格),以便提供要搜索的目录(即: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. 再说一次,就像使用Java中的几乎所有东西一样,可以用许多种不同的方式来完成几件事,但是我觉得这里呈现代码的方式相对容易遵循,并且可以根据需要进行优化。

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;
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM