[英]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. 我知道可以在命令提示符下使用命令“ * .ext * .newext”来完成此操作,但是这对我来说是不可能的解决方案,我需要重命名嵌套在此文件夹中的2,719个文件扩展名。
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.
抱歉,如果它不是最优雅的代码,我的Java有点生锈。
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 SwapFileExt参数
path
the parent directory you want to parse path
要解析的父目录 cExt
the extension type that you want to replace cExt
您要替换的扩展名类型 nExt
the desired extension type nExt
扩展所需的扩展名类型 NOTE: Both cExt
and nExt
are to be represented without the ' . 注意:
cExt
和nExt
都将不带'表示。 ' (eg "txt", not ".txt") '(例如“ txt”, 而不是 “ .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);
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.