Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

io

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"
}
like image 347
Blin Avatar asked Sep 06 '11 13:09

Blin


3 Answers

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.

like image 200
NPE Avatar answered Sep 21 '22 19:09

NPE


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.

like image 23
Omry Yadan Avatar answered Sep 18 '22 19:09

Omry Yadan


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.

like image 43
Alpedar Avatar answered Sep 18 '22 19:09

Alpedar