Renaming a file when renaming a directory

Trying to rename the directory name and file name.

try
    {
        File dir = new File("DIR");
        dir.mkdir();
        File file1 = new File(dir,"myfile1.txt");
        file1.createNewFile();
        File file2 = new File(dir,"myfile2.txt");
        file2.createNewFile();

        dir.renameTo(new File("myDIR"));            
        System.out.print(file1.renameTo(new File(dir,"myf1.txt")));
    }
    catch(IOException ie)
    {

    }

However, only the directory is successfully renamed, not the file name.
Can these operations not be performed simultaneously?

+4
source share
3 answers

This is due to the fact that yours dir, file1and file2point to the old path.

After completing these lines

File dir = new File("DIR");
dir.mkdir();
File file1 = new File(dir,"myfile1.txt");
file1.createNewFile();
File file2 = new File(dir,"myfile2.txt");
file2.createNewFile();

these will be the paths referenced by the variables,

dir = "DIR" // Exists
file1 = "DIR\myfile1.txt" //Exists
file2 = "DIR\myfile2.txt" //Exists

After doing

    dir.renameTo(new File("myDIR"));            

the paths referenced by the variables remain the same

dir = "DIR" // Doesn't exist anymore because it moved.
file1 = "DIR\myfile1.txt" // Doesn't exist anymore because it moved along with dir.
file2 = "DIR\myfile2.txt" // Doesn't exist anymore because it moved along with dir.

So when you call

    System.out.print(file1.renameTo(new File(dir,"myf1.txt")));

You call renameTo()to a file that does not exist, and to a directory that also does not exist. Thus, it does not necessarily work.

.exists() dir, file1 file2, false.

+4

! .

try
{
    File dir = new File("DIR");
    dir.mkdir();

dir .

    File file1 = new File(dir,"myfile1.txt");
    file1.createNewFile();
    File file2 = new File(dir,"myfile2.txt");
    file2.createNewFile();

, , dir .

    dir.renameTo(new File("myDIR"));  

, .

    System.out.print(file1.renameTo(new File(dir,"myf1.txt")));
}
catch(IOException ie)
{
    System.out.println(ie);
}

, , .

try
{
    File dir = new File("DIR");
    dir.mkdir();

    File file1 = new File(dir,"myfile1.txt");
    file1.createNewFile();
    File file2 = new File(dir,"myfile2.txt");
    file2.createNewFile();   
    System.out.print(file1.renameTo(new File(dir,"myf1.txt")));         

    dir.renameTo(new File("myDIR"));
}
catch(IOException ie)
{
    System.out.println(ie);
}

!

+1

Not this way. After you renamed the directory, the file1 and file2 objects still point to the old file path until the rest. You need to install them in the "new" files in the renamed directory.

0
source

Source: https://habr.com/ru/post/1598525/


All Articles