我正在尝试重命名具有特定扩展名的所有文件。这样可以正常工作,但是,这个过程似乎很慢,有时会冻结设备一段时间。如何让它占用更少的内存?
setContentView(R.layout.transparent_ui);
// getting SDcard root path
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
walkdir(dir);
finish();
}
public static final String[] TARGET_EXTENSIONS = { "the_video_first",
"webm", "mkv", "flv", "vob", "ogg", "drc", "gif", "gifv", "mng",
"avi", "mov", "wmv", "yuv", "rm", "rmvb", "asf", "mp4", "mpg",
"mpeg", "mpg", "mpeg", "m4v", "svi", "3gp", "3g2", "mxf",
"now_the_audio", "wav", "mp3", "wma", "ogg", "m4a",
"now_the_images", "jpg", "jpeg", "png", "bmp" };
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
fPath = fPath.replace("." + ext, ".xghost" + ext);
}
listFile[i].renameTo(new File(fPath));
}
}
}
}
答案 0 :(得分:0)
查看下面的链接,它有不同的实现
答案 1 :(得分:0)
你想做什么?,你能详细说明你的逻辑吗?为什么这个内部FOR循环运行这么多次。它应该如何成为你的最终道路?
for (String ext : TARGET_EXTENSIONS) {
fPath = fPath.replace("." + ext, ".xghost" + ext);
}
答案 2 :(得分:0)
试试这段代码。
public void walkdir(File dir) {
File listFile[] = dir.listFiles();
if (listFile != null) {
for (int i = 0; i < listFile.length; i++) {
if (listFile[i].isDirectory()) {
walkdir(listFile[i]);
} else {
String fPath = listFile[i].getPath();
for (String ext : TARGET_EXTENSIONS) {
// use string builder avoid concatenation inside a loop
String oldExt = new StringBuilder().append(".").append(ext).toString();
if (fPath.contains(oldExt)) {
String newExt = new StringBuilder().append(".xghost").append(ext).toString();
fPath = fPath.replace(oldExt, newExt);
listFile[i].renameTo( new File(fPath));
break; // no need to continue once we have replaced the extension.
}
}
}
}
}
}