🔥 删除 oConvertUtils.java 文件

This commit is contained in:
ronger 2021-01-06 16:11:34 +08:00
parent fbe909bf4e
commit 628c70ca06
3 changed files with 215 additions and 712 deletions

View File

@ -7,180 +7,178 @@ import org.springframework.web.multipart.MultipartFile;
import java.io.*;
import java.net.URLEncoder;
import java.util.Arrays;
/**
* 文件操作工具类
* @author 张代浩
*
* @author 张代浩
*/
public class FileUtils {
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
/**
* 获取文件扩展名
*
* @param filename
* @return
*/
public static String getExtend(String filename) {
return getExtend(filename, "");
}
private static final Logger logger = LoggerFactory.getLogger(FileUtils.class);
/**
* 获取文件扩展名
*
* @param filename
* @return
*/
public static String getExtend(String filename, String defExt) {
if ((filename != null) && (filename.length() > 0)) {
int i = filename.lastIndexOf('.');
/**
* 获取文件扩展名
*
* @param filename
* @return
*/
public static String getExtend(String filename) {
return getExtend(filename, "");
}
if ((i > 0) && (i < (filename.length() - 1))) {
return (filename.substring(i+1)).toLowerCase();
}
}
return defExt.toLowerCase();
}
/**
* 获取文件扩展名
*
* @param filename
* @return
*/
public static String getExtend(String filename, String defExt) {
if ((filename != null) && (filename.length() > 0)) {
int i = filename.lastIndexOf('.');
/**
* 获取文件名称[不含后缀名]
*
* @param
* @return String
*/
public static String getFilePrefix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(0, splitIndex).replaceAll("\\s*", "");
}
if ((i > 0) && (i < (filename.length() - 1))) {
return (filename.substring(i + 1)).toLowerCase();
}
}
return defExt.toLowerCase();
}
/**
* 获取文件名称[不含后缀名]
* 不去掉文件目录的空格
* @param
* @return String
*/
public static String getFilePrefix2(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(0, splitIndex);
}
/**
* 获取文件名称[不含后缀名]
*
* @param
* @return String
*/
public static String getFilePrefix(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(0, splitIndex).replaceAll("\\s*", "");
}
/**
* 文件复制
*方法摘要这里一句话描述方法的用途
*@param
*@return void
*/
public static void copyFile(String inputFile,String outputFile) throws FileNotFoundException{
File sFile = new File(inputFile);
File tFile = new File(outputFile);
FileInputStream fis = new FileInputStream(sFile);
FileOutputStream fos = new FileOutputStream(tFile);
int temp = 0;
byte[] buf = new byte[10240];
/**
* 获取文件名称[不含后缀名]
* 不去掉文件目录的空格
*
* @param
* @return String
*/
public static String getFilePrefix2(String fileName) {
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(0, splitIndex);
}
/**
* 文件复制
* 方法摘要这里一句话描述方法的用途
*
* @param
* @return void
*/
public static void copyFile(String inputFile, String outputFile) throws FileNotFoundException {
File sFile = new File(inputFile);
File tFile = new File(outputFile);
FileInputStream fis = new FileInputStream(sFile);
FileOutputStream fos = new FileOutputStream(tFile);
int temp = 0;
byte[] buf = new byte[10240];
try {
while((temp = fis.read(buf))!=-1){
fos.write(buf, 0, temp);
while ((temp = fis.read(buf)) != -1) {
fos.write(buf, 0, temp);
}
} catch (IOException e) {
e.printStackTrace();
} finally{
} finally {
try {
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
fis.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 判断文件是否为图片<br>
* <br>
*
* @param filename
* 文件名<br>
* 判断具体文件类型<br>
* @return 检查后的结果<br>
* @throws Exception
*/
public static boolean isPicture(String filename) {
// 文件名称为空的场合
if (StringUtils.isBlank(filename)) {
// 返回不和合法
return false;
}
// 获得文件后缀名
//String tmpName = getExtend(filename);
String tmpName = filename;
// 声明图片后缀名数组
String imgeArray[][] = { { "bmp", "0" }, { "dib", "1" },
{ "gif", "2" }, { "jfif", "3" }, { "jpe", "4" },
{ "jpeg", "5" }, { "jpg", "6" }, { "png", "7" },
{ "tif", "8" }, { "tiff", "9" }, { "ico", "10" } };
// 遍历名称数组
for (int i = 0; i < imgeArray.length; i++) {
// 判断单个类型文件的场合
if (imgeArray[i][0].equals(tmpName.toLowerCase())) {
return true;
}
}
return false;
}
}
/**
* 判断文件是否为DWG<br>
* <br>
*
* @param filename
* 文件名<br>
* 判断具体文件类型<br>
* @return 检查后的结果<br>
* @throws Exception
*/
public static boolean isDwg(String filename) {
// 文件名称为空的场合
if (oConvertUtils.isEmpty(filename)) {
// 返回不和合法
return false;
}
// 获得文件后缀名
String tmpName = getExtend(filename);
// 声明图片后缀名数组
if (tmpName.equals("dwg")) {
return true;
}
return false;
}
/**
* 判断文件是否为图片<br>
* <br>
*
* @param filename 文件名<br>
* 判断具体文件类型<br>
* @return 检查后的结果<br>
* @throws Exception
*/
public static boolean isPicture(String filename) {
// 文件名称为空的场合
if (StringUtils.isBlank(filename)) {
// 返回不和合法
return false;
}
// 获得文件后缀名
//String tmpName = getExtend(filename);
String tmpName = filename;
// 声明图片后缀名数组
String[] imageArray = {"bmp", "dib", "gif", "jfif", "jpe",
"jpeg", "jpg", "png", "tif", "tiff", "ico"};
// 遍历名称数组
for (String s : imageArray) {
if (s.equals(tmpName)) {
return true;
}
}
return false;
}
/**
* 删除指定的文件
*
* @param strFileName
* 指定绝对路径的文件名
* @return 如果删除成功true否则false
*/
public static boolean delete(String strFileName) {
File fileDelete = new File(strFileName);
/**
* 判断文件是否为DWG<br>
* <br>
*
* @param filename 文件名<br>
* 判断具体文件类型<br>
* @return 检查后的结果<br>
* @throws Exception
*/
public static boolean isDwg(String filename) {
// 文件名称为空的场合
if (StringUtils.isEmpty(filename)) {
// 返回不和合法
return false;
}
// 获得文件后缀名
String tmpName = getExtend(filename);
// 声明图片后缀名数组
if ("dwg".equals(tmpName)) {
return true;
}
return false;
}
if (!fileDelete.exists() || !fileDelete.isFile()) {
logger.info("错误: " + strFileName + "不存在!");
return false;
}
/**
* 删除指定的文件
*
* @param strFileName 指定绝对路径的文件名
* @return 如果删除成功true否则false
*/
public static boolean delete(String strFileName) {
File fileDelete = new File(strFileName);
//LogUtil.info("--------成功删除文件---------"+strFileName);
return fileDelete.delete();
}
if (!fileDelete.exists() || !fileDelete.isFile()) {
logger.info("错误: " + strFileName + "不存在!");
return false;
}
/**
*
* @Title: encodingFileName 2015-11-26 huangzq add
* @Description: 防止文件名中文乱码含有空格时%20
* @param @param fileName
* @param @return 设定文件
* @return String 返回类型
* @throws
*/
public static String encodingFileName(String fileName) {
//LogUtil.info("--------成功删除文件---------"+strFileName);
return fileDelete.delete();
}
/**
* @param @param fileName
* @param @return 设定文件
* @return String 返回类型
* @throws
* @Title: encodingFileName 2015-11-26 huangzq add
* @Description: 防止文件名中文乱码含有空格时%20
*/
public static String encodingFileName(String fileName) {
String returnFileName = "";
try {
returnFileName = URLEncoder.encode(fileName, "UTF-8");
@ -198,67 +196,69 @@ public class FileUtils {
/**
* 根据现有路径获取SWF文件名称
*
* @author taoYan
* @since 2018年7月26日
*/
public static String getSwfPath(String path){
String leftSlash = "/";
if(!File.separator.equals(leftSlash)){
path = path.replace(File.separator,leftSlash);
}
String fileDir = path.substring(0,path.lastIndexOf(leftSlash)+1);//文件目录带/
int pointPosition = path.lastIndexOf(".");
String fileName = path.substring(path.lastIndexOf(leftSlash)+1,pointPosition);//文件名不带后缀
String swfName = "";//PinyinUtil.getPinYinHeadChar(fileName);// 取文件名首字母作为SWF文件名
return fileDir+swfName+".swf";
public static String getSwfPath(String path) {
String leftSlash = "/";
if (!File.separator.equals(leftSlash)) {
path = path.replace(File.separator, leftSlash);
}
String fileDir = path.substring(0, path.lastIndexOf(leftSlash) + 1);//文件目录带/
int pointPosition = path.lastIndexOf(".");
String fileName = path.substring(path.lastIndexOf(leftSlash) + 1, pointPosition);//文件名不带后缀
String swfName = "";//PinyinUtil.getPinYinHeadChar(fileName);// 取文件名首字母作为SWF文件名
return fileDir + swfName + ".swf";
}
/**
* 上传txt文件防止乱码
*
* @author taoYan
* @since 2018年7月26日
*/
public static void uploadTxtFile(MultipartFile mf, String savePath) throws IOException{
//利用utf-8字符集的固定首行隐藏编码原理
//Unicode:FF FE UTF-8:EF BB
byte[] allbytes = mf.getBytes();
try{
String head1 = toHexString(allbytes[0]);
//System.out.println(head1);
String head2 = toHexString(allbytes[1]);
//System.out.println(head2);
if("ef".equals(head1) && "bb".equals(head2)){
//UTF-8
String contents = new String(mf.getBytes(),"UTF-8");
if(StringUtils.isNotBlank(contents)){
OutputStream out = new FileOutputStream(savePath);
out.write(contents.getBytes());
out.close();
}
} else {
public static void uploadTxtFile(MultipartFile mf, String savePath) throws IOException {
//利用utf-8字符集的固定首行隐藏编码原理
//Unicode:FF FE UTF-8:EF BB
byte[] allbytes = mf.getBytes();
try {
String head1 = toHexString(allbytes[0]);
//System.out.println(head1);
String head2 = toHexString(allbytes[1]);
//System.out.println(head2);
if ("ef".equals(head1) && "bb".equals(head2)) {
//UTF-8
String contents = new String(mf.getBytes(), "UTF-8");
if (StringUtils.isNotBlank(contents)) {
OutputStream out = new FileOutputStream(savePath);
out.write(contents.getBytes());
out.close();
}
} else {
//GBK
String contents = new String(mf.getBytes(),"GBK");
OutputStream out = new FileOutputStream(savePath);
out.write(contents.getBytes());
out.close();
//GBK
String contents = new String(mf.getBytes(), "GBK");
OutputStream out = new FileOutputStream(savePath);
out.write(contents.getBytes());
out.close();
}
} catch(Exception e){
String contents = new String(mf.getBytes(),"UTF-8");
if(StringUtils.isNotBlank(contents)){
OutputStream out = new FileOutputStream(savePath);
out.write(contents.getBytes());
out.close();
}
}
}
} catch (Exception e) {
String contents = new String(mf.getBytes(), "UTF-8");
if (StringUtils.isNotBlank(contents)) {
OutputStream out = new FileOutputStream(savePath);
out.write(contents.getBytes());
out.close();
}
}
}
public static String toHexString(int index){
public static String toHexString(int index) {
String hexString = Integer.toHexString(index);
// 1个byte变成16进制的只需要2位就可以表示了取后面两位去掉前面的符号填充
hexString = hexString.substring(hexString.length() -2);
hexString = hexString.substring(hexString.length() - 2);
return hexString;
}
}
}

View File

@ -6,13 +6,15 @@ import com.rymcu.forest.jwt.def.JwtConstants;
import com.rymcu.forest.jwt.model.TokenModel;
import com.rymcu.forest.jwt.service.TokenManager;
import com.rymcu.forest.mapper.UserMapper;
import com.rymcu.forest.web.api.exception.ErrorCode;
import com.rymcu.forest.web.api.exception.BaseApiException;
import com.rymcu.forest.web.api.exception.ErrorCode;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureException;
import org.apache.commons.lang.StringUtils;
import java.util.Objects;
/**
* @author ronger
*/
@ -31,14 +33,14 @@ public class UserUtils {
return null;
}
// 验证token
Claims claims = null;
Claims claims;
try {
claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(authHeader).getBody();
} catch (final SignatureException e) {
throw new BaseApiException(ErrorCode.UNAUTHORIZED);
}
Object account = claims.getId();
if (!oConvertUtils.isEmpty(account)) {
if (StringUtils.isNotBlank(Objects.toString(account, ""))) {
TokenModel model = tokenManager.getToken(authHeader, account.toString());
if (tokenManager.checkToken(model)) {
return userMapper.findByAccount(account.toString());
@ -52,14 +54,14 @@ public class UserUtils {
public static TokenUser getTokenUser(String token) {
if(StringUtils.isNotBlank(token)){
// 验证token
Claims claims = null;
Claims claims;
try {
claims = Jwts.parser().setSigningKey(JwtConstants.JWT_SECRET).parseClaimsJws(token).getBody();
} catch (final SignatureException e) {
return null;
}
Object account = claims.getId();
if (!oConvertUtils.isEmpty(account)) {
if (StringUtils.isNotBlank(Objects.toString(account, ""))) {
TokenModel model = tokenManager.getToken(token, account.toString());
if (tokenManager.checkToken(model)) {
User user = userMapper.findByAccount(account.toString());

View File

@ -1,499 +0,0 @@
package com.rymcu.forest.util;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.sql.Date;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
* @author 张代浩
*
*/
public class oConvertUtils {
public static boolean isEmpty(Object object) {
if (object == null) {
return (true);
}
if (object.equals("")) {
return (true);
}
if (object.equals("null")) {
return (true);
}
return (false);
}
public static boolean isNotEmpty(Object object) {
if (object != null && !object.equals("") && !object.equals("null")) {
return (true);
}
return (false);
}
public static String decode(String strIn, String sourceCode, String targetCode) {
String temp = code2code(strIn, sourceCode, targetCode);
return temp;
}
public static String StrToUTF(String strIn, String sourceCode, String targetCode) {
strIn = "";
try {
strIn = new String(strIn.getBytes("ISO-8859-1"), "GBK");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return strIn;
}
private static String code2code(String strIn, String sourceCode, String targetCode) {
String strOut = null;
if (strIn == null || (strIn.trim()).equals("")) {
return strIn;
}
try {
byte[] b = strIn.getBytes(sourceCode);
for (int i = 0; i < b.length; i++) {
System.out.print(b[i] + " ");
}
strOut = new String(b, targetCode);
} catch (Exception e) {
e.printStackTrace();
return null;
}
return strOut;
}
public static int getInt(String s, int defval) {
if (s == null || s == "") {
return (defval);
}
try {
return (Integer.parseInt(s));
} catch (NumberFormatException e) {
return (defval);
}
}
public static int getInt(String s) {
if (s == null || s == "") {
return 0;
}
try {
return (Integer.parseInt(s));
} catch (NumberFormatException e) {
return 0;
}
}
public static int getInt(String s, Integer df) {
if (s == null || s == "") {
return df;
}
try {
return (Integer.parseInt(s));
} catch (NumberFormatException e) {
return 0;
}
}
public static Integer[] getInts(String[] s) {
Integer[] integer = new Integer[s.length];
if (s == null) {
return null;
}
for (int i = 0; i < s.length; i++) {
integer[i] = Integer.parseInt(s[i]);
}
return integer;
}
public static double getDouble(String s, double defval) {
if (s == null || s == "") {
return (defval);
}
try {
return (Double.parseDouble(s));
} catch (NumberFormatException e) {
return (defval);
}
}
public static double getDou(Double s, double defval) {
if (s == null) {
return (defval);
}
return s;
}
public static Short getShort(String s) {
if (StringUtils.isNotEmpty(s)) {
return (Short.parseShort(s));
} else {
return null;
}
}
public static int getInt(Object object, int defval) {
if (isEmpty(object)) {
return (defval);
}
try {
return (Integer.parseInt(object.toString()));
} catch (NumberFormatException e) {
return (defval);
}
}
public static int getInt(BigDecimal s, int defval) {
if (s == null) {
return (defval);
}
return s.intValue();
}
public static Integer[] getIntegerArry(String[] object) {
int len = object.length;
Integer[] result = new Integer[len];
try {
for (int i = 0; i < len; i++) {
result[i] = new Integer(object[i].trim());
}
return result;
} catch (NumberFormatException e) {
return null;
}
}
public static String getString(String s) {
return (getString(s, ""));
}
/**
* 转义成Unicode编码
* @param s
* @return
*/
public static String escapeJava(Object s) {
return StringEscapeUtils.escapeJava(getString(s));
}
public static String getString(Object object) {
if (isEmpty(object)) {
return "";
}
return (object.toString().trim());
}
public static String getString(int i) {
return (String.valueOf(i));
}
public static String getString(float i) {
return (String.valueOf(i));
}
public static String getString(String s, String defval) {
if (isEmpty(s)) {
return (defval);
}
return (s.trim());
}
public static String getString(Object s, String defval) {
if (isEmpty(s)) {
return (defval);
}
return (s.toString().trim());
}
public static long stringToLong(String str) {
Long test = new Long(0);
try {
test = Long.valueOf(str);
} catch (Exception e) {
}
return test.longValue();
}
/**
* 获取本机IP
*/
public static String getIp() {
String ip = null;
try {
InetAddress address = InetAddress.getLocalHost();
ip = address.getHostAddress();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return ip;
}
/**
* 判断一个类是否为基本数据类型
*
* @param clazz
* 要判断的类
* @return true 表示为基本数据类型
*/
private static boolean isBaseDataType(Class clazz) throws Exception {
return (clazz.equals(String.class) || clazz.equals(Integer.class) || clazz.equals(Byte.class) || clazz.equals(Long.class) || clazz.equals(Double.class) || clazz.equals(Float.class) || clazz.equals(Character.class) || clazz.equals(Short.class) || clazz.equals(BigDecimal.class) || clazz.equals(BigInteger.class) || clazz.equals(Boolean.class) || clazz.equals(Date.class) || clazz.isPrimitive());
}
/**
* @param request
* IP
* @return IP Address
*/
public static String getIpAddrByRequest(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}
/**
* @return 本机IP
* @throws SocketException
*/
public static String getRealIp() throws SocketException {
String localip = null;// 本地IP如果没有配置外网IP则返回它
String netip = null;// 外网IP
Enumeration<NetworkInterface> netInterfaces = NetworkInterface.getNetworkInterfaces();
InetAddress ip = null;
boolean finded = false;// 是否找到外网IP
while (netInterfaces.hasMoreElements() && !finded) {
NetworkInterface ni = netInterfaces.nextElement();
Enumeration<InetAddress> address = ni.getInetAddresses();
while (address.hasMoreElements()) {
ip = address.nextElement();
if (!ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 外网IP
netip = ip.getHostAddress();
finded = true;
break;
} else if (ip.isSiteLocalAddress() && !ip.isLoopbackAddress() && ip.getHostAddress().indexOf(":") == -1) {// 内网IP
localip = ip.getHostAddress();
}
}
}
if (netip != null && !"".equals(netip)) {
return netip;
} else {
return localip;
}
}
/**
* java去除字符串中的空格回车换行符制表符
*
* @param str
* @return
*/
public static String replaceBlank(String str) {
String dest = "";
if (str != null) {
Pattern p = Pattern.compile("\\s*|\t|\r|\n");
Matcher m = p.matcher(str);
dest = m.replaceAll("");
}
return dest;
}
/**
* 判断元素是否在数组内
*
* @param substring
* @param source
* @return
*/
public static boolean isIn(String substring, String[] source) {
if (source == null || source.length == 0) {
return false;
}
for (int i = 0; i < source.length; i++) {
String aSource = source[i];
if (aSource.equals(substring)) {
return true;
}
}
return false;
}
/**
* 获取Map对象
*/
public static Map<Object, Object> getHashMap() {
return new HashMap<Object, Object>();
}
/**
* SET转换MAP
*
* @param str
* @return
*/
public static Map<Object, Object> SetToMap(Set<Object> setobj) {
Map<Object, Object> map = getHashMap();
for (Iterator iterator = setobj.iterator(); iterator.hasNext();) {
Map.Entry<Object, Object> entry = (Map.Entry<Object, Object>) iterator.next();
map.put(entry.getKey().toString(), entry.getValue() == null ? "" : entry.getValue().toString().trim());
}
return map;
}
public static boolean isInnerIP(String ipAddress) {
boolean isInnerIp = false;
long ipNum = getIpNum(ipAddress);
/**
* 私有IPA类 10.0.0.0-10.255.255.255 B类 172.16.0.0-172.31.255.255 C类 192.168.0.0-192.168.255.255 当然还有127这个网段是环回地址
**/
long aBegin = getIpNum("10.0.0.0");
long aEnd = getIpNum("10.255.255.255");
long bBegin = getIpNum("172.16.0.0");
long bEnd = getIpNum("172.31.255.255");
long cBegin = getIpNum("192.168.0.0");
long cEnd = getIpNum("192.168.255.255");
isInnerIp = isInner(ipNum, aBegin, aEnd) || isInner(ipNum, bBegin, bEnd) || isInner(ipNum, cBegin, cEnd) || ipAddress.equals("127.0.0.1");
return isInnerIp;
}
private static long getIpNum(String ipAddress) {
String[] ip = ipAddress.split("\\.");
long a = Integer.parseInt(ip[0]);
long b = Integer.parseInt(ip[1]);
long c = Integer.parseInt(ip[2]);
long d = Integer.parseInt(ip[3]);
long ipNum = a * 256 * 256 * 256 + b * 256 * 256 + c * 256 + d;
return ipNum;
}
private static boolean isInner(long userIp, long begin, long end) {
return (userIp >= begin) && (userIp <= end);
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式
* 如果转换前的下划线大写方式命名的字符串为空则返回空字符串</br>
* 例如hello_world->helloWorld
*
* @param name
* 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String camelName(String name) {
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty()) {
// 没必要转换
return "";
} else if (!name.contains("_")) {
// 不含下划线仅将首字母小写
return name.substring(0, 1).toLowerCase() + name.substring(1).toLowerCase();
}
// 用下划线将原始字符串分割
String camels[] = name.split("_");
for (String camel : camels) {
// 跳过原始字符串中开头结尾的下换线或双重下划线
if (camel.isEmpty()) {
continue;
}
// 处理真正的驼峰片段
if (result.length() == 0) {
// 第一个驼峰片段全部字母都小写
result.append(camel.toLowerCase());
} else {
// 其他的驼峰片段首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
}
return result.toString();
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式
* 如果转换前的下划线大写方式命名的字符串为空则返回空字符串</br>
* 例如hello_world,test_id->helloWorld,testId
*
* @param names
* 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String camelNames(String names) {
if(names==null||names.equals("")){
return null;
}
StringBuffer sf = new StringBuffer();
String[] fs = names.split(",");
for (String field : fs) {
field = camelName(field);
sf.append(field + ",");
}
String result = sf.toString();
return result.substring(0, result.length() - 1);
}
/**
* 将下划线大写方式命名的字符串转换为驼峰式(首字母写)
* 如果转换前的下划线大写方式命名的字符串为空则返回空字符串</br>
* 例如hello_world->HelloWorld
*
* @param name
* 转换前的下划线大写方式命名的字符串
* @return 转换后的驼峰式命名的字符串
*/
public static String camelNameCapFirst(String name) {
StringBuilder result = new StringBuilder();
// 快速检查
if (name == null || name.isEmpty()) {
// 没必要转换
return "";
} else if (!name.contains("_")) {
// 不含下划线仅将首字母小写
return name.substring(0, 1).toUpperCase() + name.substring(1).toLowerCase();
}
// 用下划线将原始字符串分割
String camels[] = name.split("_");
for (String camel : camels) {
// 跳过原始字符串中开头结尾的下换线或双重下划线
if (camel.isEmpty()) {
continue;
}
// 其他的驼峰片段首字母大写
result.append(camel.substring(0, 1).toUpperCase());
result.append(camel.substring(1).toLowerCase());
}
return result.toString();
}
}