8

Disregarding my last post, I've found the source of the problem. I'm using

a.renameTo(b)

when b doesn't exist. The reason it doesn't exist is because there is a symbolic link so if b is /usr/name/folder/file, then b really is /mnt/MountTest because the symlink is to that directory.

So the question is, is there an alternative way to rename a file in Java using a string value? If not, how can this rename procedure be done differently?

Hristo
  • 45,559
  • 65
  • 163
  • 230

5 Answers5

6

A rename would rename it... if it were on the same filesystem.

If a renameTo() fails, you'll need to copy it to the new location, then delete the original.

Dean J
  • 39,360
  • 16
  • 67
  • 93
6

Renaming files is also highly problematic accross file systems. See http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=4073756. Commenters of the bug report posted some sample code and also pointed out that you can use Process.exec. Both Apache Commons IO and and Google Guava have utilities for safely moving files as well:

Rahul Shelke
  • 2,052
  • 4
  • 28
  • 50
big lep
  • 879
  • 6
  • 9
4

I think you are confusing things. A java.util.File doesn't represent a file on some filesystem. It represents a path to a file.

Trevor Harrison
  • 1,744
  • 1
  • 14
  • 20
3

The problem is not that a symlink is involved; the problem is that you can't atomically rename across filesystems. The meta-problem is that the Java File operations are badly designed, and don't throw proper exceptions, and provide no error codes when something fails!

Jonathan Feinberg
  • 44,698
  • 7
  • 80
  • 103
1

How about:

a.renameTo(new File("/your/path/here/");
Poindexter
  • 2,396
  • 16
  • 19
  • that won't work because the file doesn't exist in the new file path... the rename is used in a way to mimic a "mv", essentially moving the file from one directory to another – Hristo Jan 06 '10 at 17:00
  • 1
    @Hristo: Actually, that is precisely what caused me issues: people describing renameTo as the equivalent of "mv". mv is aware of file systems, whereas renameTo is not. If you attempt to mv from one disk/partition to another, it acts as a cp and rm sequence, which renameTo does not. – Ken Sep 07 '11 at 15:56