2017-08-30 53 views
-3

這裏是代碼,我想獲得最後修改的數據和時間爲這樣的文件「2017年8月30日,10:52:04」 。但是當我使用file.lastModified()它返回long.Now,我已經這樣做,但它給了我錯誤的價值。如何獲取上次修改的數據和文件的時間

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

} 
+0

以何種方式錯誤? – shmosel

+2

使用'java.util.Date','java.util.Calendar'和'SimpleDateFormat'將Long的日期作爲一個格式化的字符串 – Jens

+0

'long'是自Unix紀元以來的毫秒數的時間值 - 您可能想要對如何將其轉換爲「String」格式的值進行一些研究 – MadProgrammer

回答

0

您可以使用SimpleDateFormat下面的代碼做,

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

方面,

+0

它給出了錯誤的答案 – paras

+0

告訴我您的故事~~ – tommybee

相關問題