我可以将前缀点(“。”)成功应用于所有.gif
扩展名的文件。例如,将“my_file.gif
”重命名为“.my_file.gif
”。但是,我想使用代码再次删除此前缀点(AKA反向)。我试过了,但是不行。 (根本不删除点)下面是我的代码和我的方法 -
这是添加点前缀的代码(工作正常) -
// getting SDcard root path
File dir = new File(Environment.getExternalStorageDirectory()
.getAbsolutePath());
walkdir(dir);
}
//detect files having these extensions and rename them
public static final String[] TARGET_EXTENSIONS = { "gif"};
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) {
if (fPath.endsWith(ext)) {
putDotBeforeFileName(listFile[i]);
}
}
}
}
}
}
private String putDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
int indexOfFileNameStart = fullPath.lastIndexOf(fileName);
StringBuilder sb = new StringBuilder(fullPath);
sb.insert(indexOfFileNameStart, ".");
String myRequiredFileName = sb.toString();
file.renameTo(new File(myRequiredFileName));
return myRequiredFileName;
}
}
这是我删除不起作用的点前缀的方法(没有强制关闭) -
private String putDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
int indexOfDot = fullPath.indexOf(".");
String myRequiredFileName = "";
if (indexOfDot == 0 && fileName.length() > 1) {
myRequiredFileName = file.getParent() + "/" + fileName.substring(1);
}
try {
Runtime.getRuntime().exec(
"mv " + file.getAbsolutePath() + " " + myRequiredFileName);
} catch (IOException e) {
e.printStackTrace();
}
return myRequiredFileName;
}
答案 0 :(得分:1)
试试此代码
private String removeDotBeforeFileName(File file) {
String fileName = file.getName();
String fullPath = file.getAbsolutePath();
String myRequiredFileName = "";
if (fileName.length() > 1 && fullPath.charAt(0)=='.') {
myRequiredFileName = file.getParent() + "/" + fileName.substring(1);
file.renameTo(new File(myRequiredFileName));
}
return myRequiredFileName;
}