简体   繁体   中英

How to get an array of current directory listing including file/directory name, last modified, and size in Java?

I know the code below will return the current files or directories in a directory:

import java.io.File;

public class test {

  File f = null;
  String[] paths;


     // create new file
     f = new File(".");

     // array of files and directory
     paths = f.list();

     // for each name in the path array
     for(String path:paths)
     {
        // prints filename and directory name
        System.out.println(path);
     }
}

but I need to return the results like below with file size, last date modified, and filename. I am not seeing how to do this with the File class methods. Any help?

 424  May 27 14:09:03  MyCode$1.class
 535  May 27 14:09:03  MyCode$2.class
2489  May 27 14:09:03  MyCode.class
4391  May 27 14:08:57  MyCode.java
4323  May 26 14:48:17  MyCode.java~
 822  May 26 15:05:12  testcases

For example...

File f = new File(".");

File[] files = f.listFiles();

DateFormat df = new SimpleDateFormat("MMM dd HH:mm:ss");

// for each name in the path array
for (File file : files) {

    System.out.printf("%4d %s %s%n", file.length(), df.format(file.lastModified()), file.getName());

}

Which outputs something like...

   0 Oct 21 16:05:28 build
3597 Oct 21 16:04:16 build.xml
  85 Oct 21 16:04:17 manifest.mf
4096 Oct 21 16:04:16 nbproject
   0 Oct 21 16:04:16 src

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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