[EDIT] I was not able to rename my file with renameTo()
method of File
class. Okay I searched and found a question explaining the same
Also I read the Java Doc for renameTo()
which says:
Many aspects of the behavior of this method are inherently platform-dependent: The rename operation might not be able to move a file from one filesystem to another, it might not be atomic, and it might not succeed if a file with the destination abstract pathname already exists. The return value should always be checked to make sure that the rename operation was successful.
Okay, I understand that renameTo()
method is platform-dependent.
Then I created the object of FileOutputStream
and called close()
method, now I tried renameTo()
method and my file got renamed,
Question:
- I was not able to understand the reason why after creating the object of
FileOutputStream
myrenameTo()
method worked?
Environment: Windows XP, User: Administrator
Code:
File f = null;
File f1 = null;
boolean isFileRenamed = false;
try {
// create new File objects
f = new File("C:\\originalFile.txt");
f1 = new File("C:\\renamedFile.txt");
// I need to write following code to rename the file
// I tried without FileOutputStram object but then renameTo() did not work
FileOutputStream fos = new FileOutputStream(f);
fos.close();
isFileRenamed = f.renameTo(f1);
System.out.print("File renamed? " + isFileRenamed);
} catch (Exception e) {
e.printStackTrace();
}
Searching for answer why renameTo() method worked after creating object of FileOutputStram
. Also my application use Java1.6 so my option for Files
class is closed. I will have to use renameTo()
method only