我正在尝试列出目录的内容,并重命名某些文件。
public void run(String dirName) {
try {
File parDir = new File(dirName);
File[] dirContents = parDir.listFiles();
// Rename if necessary
for(File f : dirContents) {
System.out.println("f is:\n" + f.toString());
String name = f.getName();
String subbedName = name.replaceAll("\uFFFD", "_");
System.out.println("\n" + "name = " + name + ", subbedName = " + subbedName + "\n");
if(!name.equals(subbedName)) {
File newFile = new File(f.getParentFile(), subbedName);
System.out.println("newFile is:\n" + newFile.toString());
if(!f.renameTo(newFile))
System.out.println("Tried to change file name but couldn't.");
}
}
}
catch(Exception exc1) {
System.out.println("Something happened while listing and renaming directory contents: " + exc1.getMessage());
}
}
当我运行它时,我得到“ Tried to change file name but couldn't.
”我不相信Java 认为这些文件是“打开的”,所以我认为这不是原因。我什至跑过传递给方法的字符串的值在chmod 777 myDir
哪里。myDir
dirName
run
我在这里想念什么?为什么 Java 不重命名这些文件?这些是 CentOS 机器。
编辑f
:为和都添加了打印输出,newFile
如下所示:
f is:
/root/path/to/mydir/test�.txt
newFile is:
/root/path/to/mydir/test_.txt