近日有用到将文件名大写转小写,ui给的图片用驼峰命名的,看着不喜欢,用程序改成小写并添加_连接。
package tjy.xa.cn.javalib.base;
import java.io.File;
/**
* Created by wq on 2017/12/18.
*/
public class Main {
public static void main(String[] args) {
// String path = "D:\\tjy_project\\test\\hdpi";
String path = "D:\\tjy_project\\code\\ElevatorMonitorTJY\\app\\src\\main\\res\\drawable-xxhdpi";
changeUpper2Small(path);
}
public static void changeUpper2Small(String path) {
File file = new File(path);
File[] files = file.listFiles();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < files.length; i++) {
boolean isUpperCase = false;
File file1 = files[i];
String pathFile = file1.getAbsolutePath();
int index = pathFile.lastIndexOf("\\");
String oldPath = pathFile.substring(0, index + 1);
String name = pathFile.substring(index + 1);
sb.setLength(0);
for (int j = 0; j < name.length(); j++) {
char c = name.charAt(j);
if (Character.isUpperCase(c)) {
isUpperCase = true;
c = Character.toLowerCase(c);
if ((j - 1) > 0 && name.charAt(j - 1) != '_') {
sb.append("_");
}
}
sb.append(c);
}
String newName = sb.toString();
if (isUpperCase) {
file1.renameTo(new File(oldPath, newName));
System.out.println("原名称" + name);
System.out.println("新名称" + newName);
}
}
}
}