Suppose I rename file A
to file B
. Now I would like to test it.
I can test that B
exists and A
does not. However I need to make sure that B
is actually renamed A
. How can I do it in Java for both Linux and Windows.

- 41,026
- 70
- 193
- 341
-
Wouldn't you have to do some low level stuff with inodes? Beyond the scope of java. – Bathsheba Oct 14 '13 at 13:43
-
Yes, inode is what I would like to check. However I am afraid I cannot do it in Java (in portable way). – Michael Oct 14 '13 at 13:57
5 Answers
- Read the contents of file A.
- Hash it.
- Rename the file.
- Read the contents of file B.
- Hash it and compare that to the hash of file A.

- 1
- 1

- 398,270
- 210
- 566
- 880
-
-
@Michael In that case I'd [trust the boolean returned by File.renameTo(File)](http://stackoverflow.com/a/19361763/1288). – Bill the Lizard Oct 14 '13 at 14:00
-
Yes, but what if I need to test a function, which is supposed to invoke _renameTo_ ? I would like to make sure _renameTo_ is invoked. – Michael Oct 14 '13 at 14:02
You could compare the MD5 checksum of the file before and after the rename.

- 1
- 1

- 576
- 3
- 16
Why don't you just trust the boolean returned by File.renameTo(File) which indicates if the renaming worked or not?

- 106
- 5
import java.io.File;
public class Main {
public static void main(String[] args) {
File oldName = new File("C:/java1.txt");
File newName = new File("C:/java2.txt");
if(oldName.renameTo(newName)) {
System.out.println("renamed");
} else {
System.out.println("Error");
}
}
}
Now for confirmation you can store the file content in string for both the file like
String contentOld = new Scanner(new File("java1.txt")).useDelimiter("\\Z").next();
String contentNew = new Scanner(new File("java2.txt")).useDelimiter("\\Z").next();
Now compair the both string and you will get the result
contentOld.equals(contentNew)
if both have same content it will return true

- 2,650
- 5
- 31
- 49
It is simple
if(B.exists()) throw new java.io.IOException("file already exists");
boolean success = A.renameTo(B);
if (success) {
// File is successfully renamed.
}
But this way is platform dependent as API mentions : http://docs.oracle.com/javase/7/docs/api/java/io/File.html#renameTo%28java.io.File%29
Instead you can use
Files.move()
in platform independent manner , this throws relevant exceptions for you to check whether the file is really renamed or not. If the method returns the path to the target file, it has been renamed correctly, otherwise it will throw an exception. You can refer the link.

- 505
- 5
- 11