java转换中文为大小驼峰命名,下划线命名

  • Post author:
  • Post category:java


想必平时我们在建数据库时,当实施和产品甩给我们一个只有中文的命名时,是不是很头疼;还得一个一个的去百度然后转化格式;

然后我就自己写了一个工具类来转换,毕竟懒是推动科技发展的一大动力 先看效果:

将自己需要转化的字段放到一个文本上

然后就会自动在文件夹下生成转译后的两个文件

上代码:

import java.io.*;
import java.math.BigDecimal;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

/**
 * @program: Crm_jh
 * @description: 字段转换
 * @author: zhang zl
 * @created: 2022/06/13 18:50
 */
public class TransformIdea {

    private static final String BIGHOLDER = "bigHump";
    private static final String SMALLHOLDER = "smallHump";

    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
//        若不指定大驼峰 默认为小驼峰
        hump("D:\\chinese.txt", SMALLHOLDER, SMALLHOLDER);

        long endTime = System.currentTimeMillis();
        float excTime = (float) (endTime - startTime) / 1000;

        System.out.println("本次执行消耗时间:" + excTime + "s");

    }

    /**
     * @return void
     * @author Zhang zl
     * @ClassName hump C
     * @Date 2022/6/29 10:01
     * @Param [file]
     * [codeType]: bigHump,smallHump 实体
     * [column]: bigHump,smallHump 数据库
     **/
    public static void hump(String file, String codeType, String column) {
        StringBuffer stringBuffer = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new FileReader(file));

            String str, strTransform = "", baiduStr = "", strTransformToDatabase = "";
            String strArrTransform[], strArrTransformToDatabase[], baiDuArray[];
            List<String> strOf = new ArrayList<>(), strOfToDatabase = new ArrayList<>();

            System.out.println(getFormatLogString("转译中... ", 31, 0));

            while ((str = reader.readLine()) != null) {
                if (!str.equals("")) {
                    baiduStr += str + ",";
                }
            }
            System.out.println(getFormatLogString("正在开启百度翻译通道....", 31, 7));
            //                    将本行注释即可使用离线模式 但需手动翻译成英文后再进行转译 网速将影响翻译速度有关
            baiDuArray = getTranslateResult(baiduStr, "zh", "en").split(",");
            System.out.println(getFormatLogString("百度翻译完成 关闭通道....", 32, 5));
            for (int j = 0; j < baiDuArray.length; j++) {
                str = baiDuArray[j].trim();

                strArrTransform = str.split(" ");
                strArrTransformToDatabase = str.split(" ");

                strArrTransform[0] = codeType.isEmpty() ? toLowerCaseFirstOne(strArrTransform[0]) :
                        codeType.equals("bigHump") ? toUpperCaseFirstOne(strArrTransform[0]) : toLowerCaseFirstOne(strArrTransform[0]);

                strArrTransformToDatabase[0] = column.isEmpty() ? toLowerCaseFirstOne(strArrTransformToDatabase[0]) :
                        column.equals("bigHump") ? toUpperCaseFirstOne(strArrTransformToDatabase[0]) : toLowerCaseFirstOne(strArrTransformToDatabase[0]);
                ;

                if (strArrTransform.length > 0) {
                    for (int i = 1; i < strArrTransform.length; i++) {
                        strArrTransform[i] = toUpperCaseFirstOne(strArrTransform[i]);
                        strArrTransformToDatabase[i] = "_" + toLowerCaseFirstOne(strArrTransformToDatabase[i]);
                    }
                    for (int i = 0; i < strArrTransform.length; i++) {
                        strTransform += strArrTransform[i];
                        strTransformToDatabase += strArrTransformToDatabase[i];
                    }
                }

                strOf.add(strTransform);
                strOfToDatabase.add(strTransformToDatabase);
                strTransform = "";
                strTransformToDatabase = "";
            }

            System.out.println(getFormatLogString("转译完毕...", 32, 0));

            System.out.println(getFormatLogString("开始写入...", 33, 0));
            writer(strOf, new FileWriter(file.replace(".", "(翻译文本-驼峰).")));
            writer(strOfToDatabase, new FileWriter(file.replace(".", "(翻译文本-下划线).")));

            BigDecimal strOfTime = new BigDecimal(strOf.size()).multiply(new BigDecimal("27"));
            BigDecimal strOfToDatabaseTime = new BigDecimal(strOfToDatabase.size()).multiply(new BigDecimal("12"));
            BigDecimal ms = strOfTime.add(strOfToDatabaseTime);
            BigDecimal min = ms.divide(new BigDecimal("60"));

            System.out.println(getFormatLogString("本次小羽大约为您节省了" + min + "min," + ms + "s哦", 36, 1));
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    public static String toUpperCaseFirstOne(String s) {
        if (Character.isUpperCase(s.charAt(0)))
            return s;
        else
            return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
    }

    public static void writer(List<String> stringList, FileWriter filter) throws IOException {
        System.out.println(getFormatLogString("正在开启写入通道....", 36, 0));

        BufferedWriter writer = new BufferedWriter(filter);

        System.out.println(getFormatLogString("正在写入....", 35, 0));
        for (int i = 0; i < stringList.size(); i++) {
            writer.write(stringList.get(i) + "\r\n");
        }

        writer.flush();
        writer.close();

        System.out.println(getFormatLogString("写入完毕...本次写入" + stringList.size() + "个字段", 34, 0));
    }

    private static String getFormatLogString(String content, int colour, int type) {
        boolean hasType = type != 1 && type != 3 && type != 4;

        if (hasType) {
            return String.format("\033[%dm%s\033[0m", colour, content);
        } else {
            return String.format("\033[%d;%dm%s\033[0m", colour, type, content);
        }

    }

    // 对接的api为百度翻译
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";

    private static String APP_ID = "20201208000641561";

    private static String SECURITY_KEY = "fAgIxjGg8rHf5qWweIgc";

    //     发送查询
    public static String getTranslateResult(String query, String from, String to) {
//        API接口身份验证
        TransApi api = new TransApi(APP_ID, SECURITY_KEY);
        String transResultStr = api.getTransResult(query, from, to);
        JSONObject result = JSONObject.parseObject(transResultStr);
        JSONArray jsonArray = result.getJSONArray("trans_result");
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        String dst = jsonObject.getString("dst");

        return dst;
    }

}
/**
 * @program: TransformIdea
 * @description:
 * @author: zhang zl
 * @created: 2022/06/20 21:30
 */

import java.util.HashMap;
import java.util.Map;
public class TransApi {
    private static final String TRANS_API_HOST = "http://api.fanyi.baidu.com/api/trans/vip/translate";
    private String appid;
    private String securityKey;
    public TransApi(String appid, String securityKey) {
        this.appid = appid;
        this.securityKey = securityKey;
    }
    public String getTransResult(String query, String from, String to) {
        Map<String, String> params = buildParams(query, from, to);
        return HttpGet.get(TRANS_API_HOST, params);
    }
    private Map<String, String> buildParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<String, String>();
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", appid);
        // 随机数
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        // 签名
        String src = appid + query + salt + securityKey; // 加密前的原文
        params.put("sign", MD5.md5(src));
        return params;
    }
}
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.Map;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
/**
 * @program: HttpGet
 * @description:
 * @author: zhang zl
 * @created: 2022/06/20 21:05
 */
class HttpGet {
    protected static final int SOCKET_TIMEOUT = 10000; // 10S
    protected static final String GET = "GET";
    public static String get(String host, Map<String, String> params) {
        try {
            // 设置SSLContext
            SSLContext sslcontext = SSLContext.getInstance("TLS");
            sslcontext.init(null, new TrustManager[] { myX509TrustManager }, null);
            String sendUrl = getUrlWithQueryString(host, params);
            // System.out.println("URL:" + sendUrl);
            URL uri = new URL(sendUrl); // 创建URL对象
            HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
            if (conn instanceof HttpsURLConnection) {
                ((HttpsURLConnection) conn).setSSLSocketFactory(sslcontext.getSocketFactory());
            }
            conn.setConnectTimeout(SOCKET_TIMEOUT); // 设置相应超时
            conn.setRequestMethod(GET);
            int statusCode = conn.getResponseCode();
            if (statusCode != HttpURLConnection.HTTP_OK) {
                System.out.println("Http错误码:" + statusCode);
            }
            // 读取服务器的数据
            InputStream is = conn.getInputStream();
            BufferedReader br = new BufferedReader(new InputStreamReader(is));
            StringBuilder builder = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                builder.append(line);
            }
            String text = builder.toString();
            close(br); // 关闭数据流
            close(is); // 关闭数据流
            conn.disconnect(); // 断开连接
            return text;
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }
    public static String getUrlWithQueryString(String url, Map<String, String> params) {
        if (params == null) {
            return url;
        }
        StringBuilder builder = new StringBuilder(url);
        if (url.contains("?")) {
            builder.append("&");
        } else {
            builder.append("?");
        }
        int i = 0;
        for (String key : params.keySet()) {
            String value = params.get(key);
            if (value == null) { // 过滤空的key
                continue;
            }
            if (i != 0) {
                builder.append('&');
            }
            builder.append(key);
            builder.append('=');
            builder.append(encode(value));
            i++;
        }
        return builder.toString();
    }
    protected static void close(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 对输入的字符串进行URL编码, 即转换为%20这种形式
     * 
     * @param input 原文
     * @return URL编码. 如果编码失败, 则返回原文
     */
    public static String encode(String input) {
        if (input == null) {
            return "";
        }
        try {
            return URLEncoder.encode(input, "utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return input;
    }
    private static TrustManager myX509TrustManager = new X509TrustManager() {
        @Override
        public X509Certificate[] getAcceptedIssuers() {
            return null;
        }
        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
        }
    };
}

百度翻译的KEY大家最好用自己的 当然用我的也可以

求三连



版权声明:本文为Beatleschasemoon原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。