0

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.

Michael
  • 41,026
  • 70
  • 193
  • 341

5 Answers5

2
  • 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.
Community
  • 1
  • 1
Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
1

You could compare the MD5 checksum of the file before and after the rename.

See Getting a File's MD5 Checksum in Java

Community
  • 1
  • 1
Hurzelchen
  • 576
  • 3
  • 16
1

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

jend
  • 106
  • 5
1
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

SSP
  • 2,650
  • 5
  • 31
  • 49
0

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.

http://docs.oracle.com/javase/7/docs/api/java/nio/file/Files.html#move%28java.nio.file.Path,%20java.nio.file.Path,%20java.nio.file.CopyOption...%29

Harsha
  • 505
  • 5
  • 11