我正在尝试列出目录的内容,并重命名某些文件。
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.
“ 我不believeJava 认为这些文件是“开放的”,所以我认为这不是原因。我什至还跑过chmod 777 myDir
where myDir
是的值dirName
字符串传递到run
method.
我在这里缺少什么?为什么 Java 不重命名这些文件?这些是 CentOS 机器。
Edit:添加了两者的打印输出f
and newFile
,如下:
f is:
/root/path/to/mydir/test�.txt
newFile is:
/root/path/to/mydir/test_.txt
你需要创建你的新File
对象与full这些文件的路径名。所以
String name = f.getName(); // gets the name without the directory
可能应该是:
String name = f.getAbsolutePath();
(您的搜索/替换可能需要更改)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)