我需要帮助重命名目录中的所有文件和文件夹,并在原始名称前添加一个字符。
这是重命名单个文件夹的方法:
File from = new File(sdcard,".DCIM");
File to = new File(sdcard,"DCIM");
from.renameTo(to);
答案 0 :(得分:0)
所以,比如:
String path = Environment.getExternalStorageDirectory().toString()+"/MyDir";
Log.d("Files", "Path: " + path);
File f = new File(path);
File file[] = f.listFiles();
Log.d("Files", "Size: "+ file.length);
for (int i=0; i < file.length; i++)
{
file[i].renameTo(file[i].getName() + "x");
}
编辑:
要更改文件名,添加临时变量可能更清楚:
String name = file[i].getName();
name = name.substr(0, name.length() - 1);
file[i].renameTo(name);
答案 1 :(得分:0)
转到根文件夹并迭代它。只需检查您访问的文件夹是否是目录,您就可以为每个文件夹编写相同的逻辑。
public static void renameFile(String path) throws IOException {
File root = new File(path);
File[] list = root.listFiles();
if (list == null)
return;
for (File f : list) {
if (f.isDirectory()) {
File from = new File(f,"."+f.getName());
File to = new File(f,f.getName());
from.renameTo(to);
renameFile(f.getCanonicalPath());
} else {
System.out.println("File:" + f.getAbsoluteFile());
}
}
}
public static void main(String[] args) throws IOException {
//Root path within which you want to change the folder names
renameFile("c:\rootPath");
}
请检查这是否对您有所帮助。