简体   繁体   中英

How to get last Modified Data & time for a file

Here is the code, I am trying to get last modified data and time for a file like this "30 August 2017, 10:52:04". but when i used file.lastModified() it returns the long.Now, I have done this but it gives me wrong value.

   public class FileEx {

    public static void main(String[] args)  {
        try{
        File file=new File("D://task2");
        if(file.isFile()){
            System.out.println("file exists");
            System.out.println("abs pth ="+file.getAbsolutePath());
            System.out.println("pth= "+file.getCanonicalPath());
        }
        else if (file.isDirectory()){
            System.out.println("directory");
            System.out.println("abs pth ="+file.getAbsolutePath());
            System.out.println("pth= "+file.getCanonicalPath());
            System.out.println("can write="+file.canWrite());
            System.out.println("parent file="+file.getParentFile());
            Date d = new Date(file.lastModified());
            System.out.println("modified="+ file.lastModified()+"time="+d);
            System.out.println("parent="+file.getParent());
            System.out.println("name ="+file.getName());
            System.out.println("usuable space: "+file.getUsableSpace()/(1024*1024*1024));
            System.out.println("total space: "+file.getTotalSpace()/(1024*1024*1024));
            System.out.println("free space: "+file.getFreeSpace()/(1024*1024*1024));

        }
        else{
            file.createNewFile();
        }

        }catch(IOException io){
            io.printStackTrace();
        }
    }

}

You can do with following code using SimpleDateFormat ,

java.text.SimpleDateFormat sf = new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS");
System.out.println("modified="
+ sf.format(new java.util.Date(file.lastModified()))+"  time="+d);

Regard,

You will need SimpleDateFormat to achieve this. It is easy.

File file = new File("\home\noname\xyz.txt");
String fileName = file.getAbsoluteFile().getName(); 
long fileLastModifiedDate = file.lastModified(); 
// returns last modified date in long format 
System.out.println(fileLastModifiedDate); 
// e.g. 1644199079746
Date date = new Date(fileLastModifiedDate); 
// create date object which accept long
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd MMM yyyy hh:mm:ss"); 
// this is the format you wanted : ‎30 ‎August ‎2017, ‏‎10:52:04
String myDate = simpleDateFormat.format(date); 
// accepts date and returns String value
System.out.println("Last Modified Date" + myDate); 
// displays: 30 ‎August ‎2017, ‏‎10:52:04

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