iboan iboan - 7 months ago 20
Java Question

How to swap filenames in directory?

I am trying to do such task using that piece of code:

File copyOfFirstVar= tmp1;
File copyOfSecondVar= tmp2;

File tmpVar = File.createTempFile("temp", "tempFile");

tmp1.renameTo(tmpVar)
tmp2.renameTo(copyOfFirstVar);
tmp1.renameTo(copyOfSecondVar);


where tmp1 and tmp2 are objects from File class -> files I want to rename,
but that doesn't do anything.

Answer

As was said in the comments, you are referencing several times the same File (which is the temp file).

Since :

File copyOfFirstVar= tmp1;
File copyOfSecondVar= tmp2;

Your logic becomes :

tmp1.renameTo(tmpVar);  // now tmp1 and tmpVar are references to the same file
tmp2.renameTo(tmp1);    // now tmp2 and tmp1 are references to the same file
tmp1.renameTo(tmp2);    // see above

So you end up with tmp1, tmp2 and tmpVar all three referencing the same File .

You should avoid using File references for your swapping, just use paths as String.

File copyOfFirstVar= tmp1;
File copyOfSecondVar= tmp2;

String firstPath = copyOfFirstVar.getAbsolutePath();
String secondPath = copyOfSecondVar.getAbsolutePath();

File tmpVar = File.createTempFile("temp", "tempFile");

tmp1.renameTo(tmpVar);
tmp2.renameTo(new File(firstPath));
tmp1.renameTo(new File(secondPath));

Also note as other persons pointed out, that renameTo will fail if the destination File exists.