Blin
Blin

Reputation: 698

Why File.renameTo doesn't change where File points to?

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"
}

Upvotes: 16

Views: 3858

Answers (3)

NPE
NPE

Reputation: 500427

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.

Upvotes: 16

Alpedar
Alpedar

Reputation: 1344

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.

Upvotes: 1

Omry Yadan
Omry Yadan

Reputation: 33646

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.

Upvotes: 6

Related Questions