0

I am looking for a way to convert my old file to a new file after my program processes the file. The new file should contain the current timestamp after it's been processed. For example, my old file is test.txt. After it's been processed, it should change to test2017-10-13.txt. I have searched for the solution around internet, but I still can't make it work. Here is my current source code

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



This is my sample output

The current day is :2017-10-13
false



Is it a known bug with java? I found this information online. Is there any method to do it without copying out the contents from the older file and writing it into the new file ?

phlaxyr
  • 923
  • 1
  • 8
  • 22
test
  • 39
  • 1
  • 3

4 Answers4

0

One common reason it return false is because your file is locked that's why it return false. Check if you open it in any application OR if your application itself locking it somewhere.

You can check Check if a file is locked in Java

leafy
  • 156
  • 1
  • 8
0

Try this...

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

The best practice is, to check the file exists or not first. Then, perform IO operation.

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

I'm assuming, the path, which you were using there user is just place holder and when you are running below code then you are changing it to your actual user name.

C:\\Users\\user\\Desktop\\test
Ravi
  • 30,829
  • 42
  • 119
  • 173
0

You need to set your file readable/writable. Sometime your file has read only access.

Second thing, You Should close streams (if used).

Try this:

               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());

Out put is: Hello 2017-10-12.txt

Anshu kumar
  • 407
  • 5
  • 5