我正在尋找一種方法,在我的程序處理完文件後將舊文件轉換爲新文件。新文件在處理完後應該包含當前時間戳。例如,我的舊文件是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。有沒有辦法做到這一點,而不需要從舊文件中複製內容並將其寫入新文件?
你確定 「的test.txt」 的文件存在? – Jerry06
是的,它已經存在了,因爲IOException沒有提出 – test
不,你應該調用'file.exists()'來查看。如果它不存在,'rename'將返回false – Jerry06