簡體   English   中英

文件名無法更改

[英]File Name Not Able to Change

我正在尋找一種在程序處理文件后將舊文件轉換為新文件的方法。 處理后,新文件應包含當前時間戳。 例如,我的舊文件是test.txt 處理后,應更改為test2017-10-13.txt 我已經搜索了有關Internet的解決方案,但仍然無法使它起作用。 這是我當前的源代碼

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



它是Java的已知錯誤嗎? 我在網上找到了這些信息 有什么方法可以做到,而無需從舊文件中復制內容並將其寫入新文件?

它返回false的一個常見原因是您的文件被鎖定,這就是它返回false的原因。 檢查是否在任何應用程序中將其打開,或者應用程序本身是否將其鎖定在某處。

您可以檢查檢查文件是否在Java中被鎖定

嘗試這個...

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

最佳做法是,首先檢查文件是否存在。 然后,執行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

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

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

嘗試這個:

               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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM