16
File oldFile = new File("old"); if (oldFile.renameTo(new File("new"))){ System.out.println(oldFile.getName());//this prints "old" } 

I've looked at openJDK source, and there renameTo(File dest) function looks like this:

public class File implements Serializable, Comparable<File> { static private FileSystem fs = FileSystem.getFileSystem(); private String path; ... public boolean renameTo(File dest) { SecurityManager security = System.getSecurityManager(); if (security != null) { security.checkWrite(path); security.checkWrite(dest.path); } return fs.rename(this, dest); } ... } 

So the path variable never gets changed. Why is that so? What would be the right way to use renamed File variable? Currently i do it like this:

File oldFile = new File("/home/blin/misk/old"); File newFile = new File("/home/blin/misk/new"); if (oldFile.renameTo(newFile)){ oldFile=newFile; System.out.println(oldFile.getName());//this prints "new" } 
2
  • You are doing it correctly in your last example. Commented Sep 6, 2011 at 13:19
  • File is an immutable name of a path. It doesn't have to exist and it doesn't change. Commented Sep 6, 2011 at 13:35

3 Answers 3

16

The simplest possible explanation is that, to quote the Javadoc:

Instances of the File class are immutable; that is, once created, the abstract pathname represented by a File object will never change.

As others have said, there is no right or wrong here. However, as soon as the library's designers made the above choice, the current behaviour of renameTo became the only possible one.

As to your second code snippet, I can see no flaws in it.

Sign up to request clarification or add additional context in comments.

Comments

6

A File object is just a name, it does not even have to exist. The renameTo API call actually renames the file on the file system, but does not alter the File Object because this is what the API is designed to do. there is no right or wrong here. the API designers at Sun thought that it makes more sense this way.

1 Comment

I believe I once heard someone at Sun discussing how they should have named the class Path instead of File to better clarify this...
1

From quick glance into File, it looks like its immutable. It has some setters, but they operate on actual file on filesystem, not on the File instance.

So rename not modifiing current instance keeps the same style.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.