简体   繁体   中英

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.

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.

File.createTempFile(...) will create a physical file in the "temp" folder. So renaming another file to that name will fail as file already exist.

The problem in your program is you are changing/swaping even path along with the file name, so even after you perform renameTO it actually renaming the file once again with same old name.

Below is the program to achieve what you are trying to do:

public class SwapFileName {

    public static void main(String[] args) {
        File file1 = new File("C:\\temp1\\asd.txt");
        File file2 = new File("C:\\temp2\\dsa.txt");
        boolean isSuccess = swapName(file1, file2);
        System.out.println(isSuccess);
    }
    public static boolean swapName(File tmp1, File tmp2) {
        String path1 = tmp1.getAbsolutePath().substring(0, tmp1.getAbsolutePath().lastIndexOf(File.separator)+1);
        String fileName1 = tmp2.getName();
        File swapFile1 = new File(path1 + File.separator + fileName1);

        String path2 = tmp2.getAbsolutePath().substring(0, tmp2.getAbsolutePath().lastIndexOf(File.separator)+1);
        String fileName2 = tmp1.getName();
        File swapFile2 = new File(path2 + File.separator + fileName2);

        return (tmp1.renameTo(swapFile1) && tmp2.renameTo(swapFile2));

    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM