2013-02-15 34 views
6

爲什麼下面的代碼中文件的日期沒有改變?用C爲什麼setLastModified(time)不適用於此文件?

fLocal.location =現有的文件:\

fLocal.date =日期在長

boolean x = new File(fLocal.location).setLastModified(Long.parseLong(fLocal.date)); 
System.out.println("Changed: " + x); 
System.out.println(new Date(new File(fLocal.location).lastModified())); 
System.out.println(new Date(Long.parseLong(fLocal.date))); 

輸出設置:

Changed: false 
Fri Feb 15 23:02:51 CET 2013 
Fri Feb 15 22:49:34 CET 2013 
+3

您的代碼是否具有對該文件的寫入權限?文件是否處於打開狀態? – JoshDM 2013-02-15 22:21:51

+4

您當前正在使用任何其他應用程序閱讀文件嗎?這些都是可能會阻止您更改文件時間的項目。用一行文本創建一個簡單的純文本文件,保存並關閉編輯器。然後嘗試使用該文件。確保你在你的文件對象上調用'exists()',然後試圖改變它以確保你實際上有一個有效的文件。 – JoshDM 2013-02-15 22:27:46

+0

直接在C:\下工作是一個特別糟糕的想法,因爲a)在最近的Windows版本中,您不應該觸摸/更改那裏的文件和目錄b)您可能意外覆蓋或刪除操作系統文件(如引導配置文件)。 – Ingo 2013-02-15 23:05:44

回答

2

從早期我的意見,請按照下列檢查:

  1. 您的代碼是否有寫入權限的文件?
  2. 文件是否處於打開狀態?
  3. 您目前正在閱讀(或寫作!)該文件與任何其他應用程序在你這樣做?

這些都是可能會阻止您更改文件時間的所有項目。

用一行文本創建一個簡單的純文本文件,保存並關閉編輯器。然後嘗試在您的應用程序中使用該文件。在嘗試更改它的時間以確保您確實擁有有效的文件之前,請務必在您的FileObject上致電exists()

2

測試在我的本地代碼和它的作品......我變的很舊的文件的修改日期我的系統上...

- 參見如果文件正在被別的地方... -check如果您擁有文件權限

import java.io.File; 
import java.io.IOException; 
import java.util.Date; 

class Test 
{ 
    private class flocalClass 
    { 

     public String date; 
     public String location="c:/Test/cascade.xyz"; 

    } 
    public static void main (String[]args) throws IOException 
    { 
     flocalClass fLocal = new Test().new flocalClass(); 
     fLocal.date = Long.toString(new Date().getTime()); 
     boolean x = new File(fLocal.location).setLastModified(Long.parseLong(fLocal.date)); 
     System.out.println("Changed: " + x); 
     System.out.println(new Date(new File(fLocal.location).lastModified())); 
     System.out.println(new Date(Long.parseLong(fLocal.date))); 
    } 
} 
相關問題