• Post Reply Bookmark Topic Watch Topic
  • New Topic

file.renameTo : linux v windows  RSS feed

 
Damian Harvey
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can someone tell me why this works on Windows but not on Linux if renaming to a different partition :

import java.io.*;

public class moveFile {

public static void main(String[] args) {
File f = new File(args[0]);
System.out.println("Moving file "+args[0]+" to "+args[1]);
boolean ok = f.renameTo(new File(args[1]));
System.out.println("Move file was : "+ok);

}
}

running it on Linux with :

this works : java moveFile /opt/test1/testfile /opt/test2/testfile
this doesn't : java moveFile /opt/testfile /tmp/testfile

Thanks,

D.
 
Jack Kay
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What's the name of the Exception?
IOException?
What exactly is the error message?
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you read the Javadoc for renameTo(), you'll see that it is documented to be able to fail. It returns a boolean that tells you whether it succeeds.

It is not true that on Linux this doesn't work, and on Windows it does. What is true is that whether any particular renameTo() call is going to work is a property of the implementation. It may be that in the next patchlevel of a given JDK, a call that used to fail will now succeed. It also may be that whether a given call will work or not depends on the physical OS you're running on top of, the filesystems in use, etc.

In general, expect renameTo to work within a given directory. Outside of that, anticipate that it may not.
 
Damian Harvey
Greenhorn
Posts: 12
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I realise that it returns a boolean. That's why I test for it.

Jack, there is no exception. The boolean is just set to false.

I've tested this on SuSE 8 and RedHat AS 2.1 with the same results. On windows I can renameTo across partitions, but on Linux I can't.

Is there a better alternative (better in terms of cross-platform) for moving a file to another directory? Should I just read the contents, write it out and delete the original?

Thanks.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can try renameTo(), and if it fails, then fall back to doing a copy. This is actually how UNIX "mv" is generally implemented: first try rename(2), and, failing that, copy the data.

Thinking of it, I suppose that means Sun's UNIX version of File.renameTo() just uses rename(2), which can only rename files within a filesystem.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!