File is getting locked after renameTo method (JAVA, Windows, JDK6)

366 views Asked by At

I am renaming the extension of the file from .tmp to .xml, but when I try to access the same file from other path, it gives me an exception that file is locked.

String filename= "TemporaryFile.tmp";
File file = new File(filename);
String filename1 = file.getPath().replace(".tmp",".xml");
File file1 = new File(filename1);
if(file.renameTo(file1)){
System.out.println("File is successfully renamed");
}

Here, the file gets successfully renamed but is locked by some process and couldn't be accessed for further processing. I have tried using file.canWrite(); which returns false, and even tried modifying its state with setReadable() and setExecutable() methods, but nothing works. Any help on this would be appreciated. Please note I can't use any other JDK.

1

There are 1 answers

0
Yan On
    String filename= "TemporaryFile.tmp";
    File file = new File(filename);
    String filename1 = file.getPath().replace(".tmp",".xml");
    File file1 = new File(filename1);
    if(file.renameTo(file1)){
        System.out.println("File is successfully renamed");
        System.out.println("Can write file: " + file.canWrite());
        System.out.println("Can write file1: " + file1.canWrite());

    }

the output: File is successfully renamed

Can write file: false

Can write file1: true

Java Doc: https://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo(java.io.File) Postback if that worked.