2017-10-13 106 views
0

我正在尋找一種方法,在我的程序處理完文件後將舊文件轉換爲新文件。新文件在處理完後應該包含當前時間戳。例如,我的舊文件是test.txt。處理完成後,應更改爲test2017-10-13.txt。我已經在互聯網上尋找解決方案,但我仍然無法完成工作。這裏是我當前的源代碼

文件名不可更改

LocalDate now2 = LocalDate.now(); 
System.out.println("The current day is :" +now2); 
File oldFile1 = new File("C:\\Users\\user\\Desktop\\test.txt"); 
File newFile1 = new File("C:\\Users\\user\\Desktop\\test"+now2+".txt"); 
boolean success = oldFile1.renameTo(newFile1); 
System.out.println(success); 



這是我的樣本輸出

The current day is :2017-10-13 
false 



它是一個已知的bug與Java?我在網上找到這個information。有沒有辦法做到這一點,而不需要從舊文件中複製內容並將其寫入新文件?

+0

你確定 「的test.txt」 的文件存在? – Jerry06

+0

是的,它已經存在了,因爲IOException沒有提出 – test

+0

不,你應該調用'file.exists()'來查看。如果它不存在,'rename'將返回false – Jerry06

回答

0

它返回false的一個常見原因是因爲你的文件被鎖定,這就是爲什麼它返回false。檢查你是否在任何應用程序中打開它,或者如果你的應用程序本身鎖定在某個地方

您可以檢查Check if a file is locked in Java

+0

這是非常可能的原因。在創建文件時使用file.setReadable()和file.setWritable。 –

+0

注意:在窗口中可寫僅更改「只讀」標誌,因此它不會影響文件重命名。 – leafy

0

嘗試......

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); 
     Calendar cal = Calendar.getInstance(); 
     File file = new File("D:\\test\\test1.txt"); 
     File newFile = new File("D:\\test\\test"+dateFormat.format(cal.getTime())+".txt"); 
     if(file.renameTo(newFile)){ 
      System.out.println("File rename success");; 
     }else{ 
      System.out.println("File rename failed"); 
     } 
+0

也適用於csv文件嗎? – test

+0

是的,但您需要相應地對上述代碼進行更改。 – Chandrakant

0

最好的做法是,以檢查文件是否存在或不是第一。然後,執行IO操作。

if (oldFile1.exists()) { 
     boolean success = oldFile1.renameTo(newFile1); 
     System.out.println(success); 
    } 
    else 
    { 
     System.out.println("failed"); 
    } 

我假設,路徑,您所使用的有user僅僅是佔位符,當您運行下面的代碼,那麼你就改變你的實際user名。

C:\\Users\\user\\Desktop\\test 
0

您需要設置您的文件可讀/寫。有時您的文件具有隻讀訪問權限。

第二件事,你應該關閉流(如果使用)。

試試這個:

   File f; 
       f=new File("zzzz.txt"); 
       LocalDate ld=LocalDate.now(); 

       f.renameTo(new File("Hello "+ld.toString()+".txt")); 
       System.out.println(f.getAbsoluteFile()+" "+f.exists()); 

出看跌期權: 你好2017-10-12.txt

+0

存在一個文件zzzz.txt並重命名,我在這裏使用了一個臨時文件。 –

+0

適用於任何種類的文件,包括csv文件。 –