所以我编写了一个在Unix机器上使用的小程序,它必须在存储它的目录中获取文件和文件夹的所有名称,然后从中删除所有字符。这些字符(或字符)将由用户定义。使用案例:我把程序放在包含各种无用文件和目录的目录中,例如“NaCl2 !!!!!!!!!”,“H2O!”,“O2”和“Lithium !!!!! “并且我“要求”它去掉所有直升机名字中的所有刘海,这样就会产生这样的结果:
ls
NaCl2 H2O O2 Lithium Unreal3.zip
好的,我想你明白了。所以这是代码,它不编译(
DirRename.java:18: error: method renameTo in class File cannot be applied to given types;
tempDir.renameTo(name);
)。我想这个错误是由我的代码中的实质性问题引起的。有没有办法让它发挥作用,你能告诉我吗?
import java.io.*; import java.util.Scanner;
class DirRename {
public static void main(String[] s) {
//DECLARING
String name, curDir, annoyngChar;
Scanner scan = new Scanner(System.in);
//WORKING
curDir = System.getProperty("user.dir");
File dir = new File(curDir);
File[] listOfFiles = dir.listFiles();
System.out.print("Type a character (or a line of them) that you want to remove from directories' names:");
annoyngChar = scan.nextLine();
System.out.println("\nAll directories will get rid of " + annoyngChar + " in their names.");
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory() ) {
File tempDir = listOfFiles[i];
name = tempDir.getName().replaceAll(annoyngChar, "");
tempDir.renameTo(name);
}
}
}
}
需要说,该计划尚未完成,我很抱歉。
答案 0 :(得分:0)
File.renameTo(File dest)采用File
参数,而不是String
。因此,您需要使用正确的路径(使用新名称)创建File
实例,并将该实例传递给renameTo
。
试试这个(未经测试):
import java.io.*; import java.util.Scanner;
class DirRename {
public static void main(String[] s) {
//DECLARING
String name, curDir, annoyngChar;
Scanner scan = new Scanner(System.in);
//WORKING
curDir = System.getProperty("user.dir");
File dir = new File(curDir);
File[] listOfFiles = dir.listFiles();
System.out.print("Type a character (or a line of them) that you want to remove from directories' names:");
annoyngChar = scan.nextLine();
System.out.println("\nAll directories will get rid of " + annoyngChar + " in their names.");
for (int i = 0; i < listOfFiles.length; i++) {
if (listOfFiles[i].isDirectory() ) {
File f = listOfFiles[i];
String oldName = f.getName();
name = oldName.replaceAll(annoyngChar, "");
if (!oldName.equals(name)) {
File newF = new File(dir, name);
f.renameTo(newF);
}
}
}
}
}
或者,您可以使用Files.move重命名该文件。该文档有一个示例,说明如何重命名文件,同时将文件保存在同一目录中。