How to discover a File's creation time with Java?

后端 未结 7 1134
遥遥无期
遥遥无期 2020-11-28 10:59

Is there an easy way to discover a File\'s creation time with Java? The File class only has a method to get the \"last modified\" time. According to some resources I found

7条回答
  •  南方客
    南方客 (楼主)
    2020-11-28 11:04

    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    
    
    public class CreateDateInJava {
        public static void main(String args[]) {
            try {
    
                // get runtime environment and execute child process
                Runtime systemShell = Runtime.getRuntime();
                BufferedReader br1 = new BufferedReader(new InputStreamReader(System.in));
                System.out.println("Enter filename: ");
                String fname = (String) br1.readLine();
                Process output = systemShell.exec("cmd /c dir \"" + fname + "\" /tc");
    
                System.out.println(output);
                // open reader to get output from process
                BufferedReader br = new BufferedReader(new InputStreamReader(output.getInputStream()));
    
                String out = "";
                String line = null;
    
                int step = 1;
                while ((line = br.readLine()) != null) {
                    if (step == 6) {
                        out = line;
                    }
                    step++;
                }
    
                // display process output
                try {
                    out = out.replaceAll(" ", "");
                    System.out.println("CreationDate: " + out.substring(0, 10));
                    System.out.println("CreationTime: " + out.substring(10, 16) + "m");
                } catch (StringIndexOutOfBoundsException se) {
                    System.out.println("File not found");
                }
            } catch (IOException ioe) {
                System.err.println(ioe);
            } catch (Throwable t) {
                t.printStackTrace();
            }
        }
    }
    
    /**
    D:\Foldername\Filename.Extension
    
    Ex:
    Enter Filename :
    D:\Kamal\Test.txt
    CreationDate: 02/14/2011
    CreationTime: 12:59Pm
    
    */
    

提交回复
热议问题