2017-03-11 48 views
0

我没有从继承自File类的类中得到正确的最后修改。 我的方法是这样的:文件最后修改的问题

public Date getLastModification() { 
    Calendar cal = Calendar.getInstance(); 
    cal.setTimeInMillis(lastModified()); 
    Date dateRepresentation = cal.getTime(); 
    return dateRepresentation; 
} 

当我打电话的的toString这个方法,这始终打印周四1月1 01:00:00 CET 1970年 我审阅文件的API,我不明白为什么会这样。你能帮我正确实施吗?

+0

你能显示lastModified()的代码吗? – jjj

+1

我不定义方法lastModified(),因为是File的方法,我在API中搜索 – David

回答

0

你的逻辑适合我。你应该确保你的文件存在

FileTest test = new FileTest("test.txt"); 
System.out.println("Existing:" + test.getLastModification()); 

FileTest test2 = new FileTest(""); 
System.out.println("Not existing: " + test2.getLastModification()); 

输出为:

Sat Mar 11 10:24:39 CET 2017 
File does not exist 
Thu Jan 01 01:00:00 CET 1970 

FileTest像:

public class FileTest extends File { 


    public FileTest(String pathname) { 
     super(pathname); 
    } 

    public Date getLastModification() { 
     if(!exists()){ 
      System.out.println("File does not exist"); 
     } 
     Calendar cal = Calendar.getInstance(); 
     cal.setTimeInMillis(lastModified()); 
     return cal.getTime(); 
    } 
} 
0

造成这种情况的唯一原因是文件不在路径存在为此您已创建自定义文件对象,因此在代码cal.setTimeInMillis(lastModified());lastModified()是返回ning 0,所以你会看到Calendar API的初始化本地日期。