简体   繁体   中英

Renaming files in a parent folder?

I'm curious as if there's a way to define a Parent-folder, then have a program cycle through all of the files, and sub-folders, and rename the file extension.

I know this can be done in the command prompt using the command "*.ext *.newext" however that's not a possible solution for me and I need to rename 2,719 file extentions that are nested inside of this folder.

Yes, you can do it. Here's an example:

    // java 6
    File parentDir = new File("..");
    System.out.println(parentDir.getAbsolutePath());
    final File[] files = parentDir.listFiles();
    System.out.println(Arrays.toString(files));

    // java 7+
    File parentDir = new File("..");
    try {
        Files.walkFileTree(parentDir.toPath(), new SimpleFileVisitor<Path>() {
            @Override
            public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                if (file.toFile().renameTo(new File("othername.txt"))) {
                    return FileVisitResult.CONTINUE;
                } else {
                    return FileVisitResult.TERMINATE;
                }
            }
        });
    } catch (IOException e) {
        e.printStackTrace();
    }

This one does not go through subdirs, but it is easy to modify that way.

Here's a simple function that should do the job for you. Sorry, if it's not the most elegant code -- my Java is a little rusty.

By default, it's recursive in its implementation; so be aware that it will affect all files of the specified type in the parent directory!

SwapFileExt params

  • path the parent directory you want to parse
  • cExt the extension type that you want to replace
  • nExt the desired extension type

NOTE: Both cExt and nExt are to be represented without the ' . ' (eg "txt", not ".txt")

public static void SwapFileExt(String path, String cExt, String nExt) {
    File parentDir = new File(path);
    File[] contents = parentDir.listFiles();

    for (int i = 0; i < contents.length; i++) {
        if (contents[i].isFile()) {
            if (contents[i].toString().contains("." + cExt)) {
                String item = contents[i].toString().replaceAll("." + cExt, "." + nExt);
                contents[i].renameTo(new File(item));
            }
        } else if (contents[i].isDirectory()) {
            SwapFileExt(contents[i].toString(), cExt, nExt);
        }
    }
}

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