下划线转化为驼峰命名工具类

把数据库字段名转换为驼峰命名,如:create_time 转换为: createTime 。方便在写mapper文件时使用,特别是进行insert操作时

import org.apache.commons.io.FileUtils;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;

/**
 * @describtion 把数据库字段名转换为驼峰命名
 * 如:create_time 转换为: createTime
 * @creator wangli66
 * @create-time 14:48 2019/12/23
 **/
public class NameExchangeUtil {
    public static void main(String[] args) throws IOException {
        String content = FileUtils.readFileToString(new File("G:\\test\\testName.txt"));
        System.out.println("读取到文件-----------" + content);
        String exchange = exchange(content, ",");// ","分割符
        FileUtils.writeStringToFile(new File("G:\\test\\testName.txt"), exchange);
        System.out.println("写入到文件-----------" + exchange);
    }

    /*
     * @Description: 将下划线命名转换为驼峰命名
     * @param: [sourceStr, spearator]需要替换的字符串,sperator分隔符
     * @return: java.lang.String
     * @Date: 2019/12/23
     */
    public static String exchange(String sourceStr, String spearator) {
        StringBuilder sb = new StringBuilder();
        if (sourceStr.indexOf(spearator) > 0) {
            String[] split = sourceStr.split(spearator);
            Arrays.stream(split).forEach(word -> {
                StringBuilder sb1 = parseStr(word);
                sb1.append(spearator);
                sb.append(sb1);
            });
        }else {
            StringBuilder sb1 = parseStr(sourceStr);
            sb1.append(spearator);
            sb.append(sb1);
        }
        return sb.substring(0, sb.lastIndexOf(spearator)).toString();
    }

    public static StringBuilder parseStr(String str) {
        if ("_".equals(str.charAt(0))) {
            str = str.substring(1);
        } else if ("_".equals(str.charAt(str.length() - 1))) {
            str = str.substring(0, str.length() - 1);
        }

        StringBuilder sb1 = new StringBuilder();
        String[] s = str.split("_");
        sb1.append(s[0]);
        for (int i = 1; i < s.length; i++) {
            char c = s[i].charAt(0);
            if (c >= 97) {
                c -= 32;
            }
            // 使用StringBuilder 是为了避免一个单词中出现相同字母的情况
            StringBuilder tmpsb = new StringBuilder(s[i]);
            tmpsb.replace(0, 1, String.valueOf(c));
//                    s[i] = s[i].replace(s[i].charAt(0),c);
            sb1.append(tmpsb);
        }

        return sb1;
    }
}

效果如图

转化前:

转化后:

 

已标记关键词 清除标记
相关推荐
©️2020 CSDN 皮肤主题: 深蓝海洋 设计师:CSDN官方博客 返回首页