Skip to Main Content

New to Java

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

Why doesn't renameTo() of File Class not rename a file ?

843789Feb 4 2010 — edited Feb 4 2010
Hi Folks,

This is my code :
package file;

import java.io.File;
import java.io.IOException;

public class File1 
{
	public static void main(String[] args) {
		File objFile=new File("C:\\file1.txt");
		File objFile2=new File("C:\\");
		File objFileNewName=new File("C:\\file2.txt");
		File objDirNew=new File("C:\\TOPGEAR");

		System.out.println("File Name="+objFile.getName());
		System.out.println("File Path="+objFile.getPath());


		try {
			System.out.println("File Successfully Created="+objFile.createNewFile());

			System.out.println("File Renamed="+objFile.renameTo(objFileNewName);
			System.out.println("File Name="+objFile.getName());
			
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}

O/P :
File Name=file1.txt
File Path=C:\file1.txt
File Successfully Created=true
File Renamed=true
File Name=file1.txt
My question is :

Even though the file is renamed as "file2.txt" on the system,why doesn't the new name get reflected when I call the getFileName() on the same file object ?

Thank you for your time.
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Mar 4 2010
Added on Feb 4 2010
23 comments
954 views