简体   繁体   中英

Error in Renaming Files

Although there are many questions here that involve errors with naming files, the code below tries to implement those examples but fails to actually change the name of the file in the system for no apparent reason.

public static void main(String[] args)
{
    File dir = new File("E:/Vglut2 pharmacology/60730/");
    File[] directoryListing = dir.listFiles();
    for (File filius : directoryListing) {
        try
        {
            String oldName = filius.getName();
            int imgNum = returnImageNumber(oldName);
            double imgMag = returnImageMagnification(oldName);
            String newName = oldName.substring(0, oldName.indexOf('_')).concat('_' + String.valueOf(imgNum)).concat('_' + String.valueOf(imgMag));
            File nova = new File(newName);
            filius.renameTo(nova);
            System.out.println(newName);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }

    }
}

The resulting string that I tested by printing offers the desired resulting final name, however, in the end, the filesystem remains unchanged. A similar example from a previous stack overflow question is as seen below-

File dir = new File("D:/xyz");

if (dir.isDirectory()) { // make sure it's a directory
for (final File f : dir.listFiles()) {
    try {
        File newfile =new File("newfile.txt");

        if(f.renameTo(newfile)){
            System.out.println("Rename succesful");
        }else{
            System.out.println("Rename failed");
        }
    } catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
}

As seen there are no significant differences that I can tell which would affect the viability of this process. Note I am running Windows 10 Home edition as an admin if this is related. Thanks for the help.

filius.getName() only gets the last part of the files path. renameTo on the other hand needs the full path. So in fact you end up trying to move your file into a different directory.

Use:

File nova = new File(dir, newName);

in order to rename the file in the original directory.

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