字符串工具类

package com.zq.utils.string;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;

 

/**
*
* 字符串工具类
*
* Created by MyEclipse. Author: ChenBin E-mail: chenb@8000056.com Date:
* 2016-6-17 Time: 上午11:36:06 Company: HuNan BwWan information technology
* co.,LTD Web sites: http://www.8000056.com/
*/
public class StringUtils {
private static Logger logger = Logger.getLogger(StringUtils.class);
/**
* 空格
*/
public static final String SPACING = " ";
/**
* 空字符串
*/
public static final String EMPTY_STR = "";
/**
* email正则表达式
*/
public static final String REGEX_EMAIL = "^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$";
/**
* 浮点数或者整数表达式
*/
public static final String REGEX_NUMBER = "^\\-?\\d+((\\.\\d+)|\\d*)$";
/**
* 纯数字正则表达式
*/
public static final String REGEX_INT = "^[0-9]*$";
/**
* 严格手机号码判断(合法手机号 11位 13 14 15 18开头)
*/
public static final String REGEX_MOBILE = "^(13|14|15|18)\\d{9}$";
/**
* 仅能包含数字、字母和下划线
*/
public static final String REGEX_USERNAME = "[A-Za-z0-9_]+";

private StringUtils() {
}

// public static void main(String[] args) {
// Map<String, String> map = new HashMap<String, String>();
// map.put("a", "1");
// map.put("b", "2");
// Lang.convertMapKey(map, new MapKeyConvertor() {
// @Override
// public String convertKey(String key) {
// System.out.println(key);
// return key + 1;
// }
// }, true);
// System.out.println(Json.toJson(map));
// String str = "asdf32dfdsdfs";
// System.out.println(Lang.md5(str));
// System.out.println("a68e079ddfec7ac3a8e76d0a78a5732b".length());
// System.out.println(Lang.isAndroid);
// String rootPath = Lang.runRootPath();
//// File file = new File(rootPath);
//// File f = Files.getFile(file, "init/citys.json");
// String json = Files.read(rootPath + "init/citys.json");
// List<SysAreaDict> list =Json.fromJsonAsList(SysAreaDict.class, json);
// System.out.println(Json.toJson(list.get(12)));
// }

/**
* Description :单个/批量判断是否为空
*
* @author : ChenBin
* @date : 2016-6-17 上午11:38:00
*/
public static boolean compareTrim(String... args) {// 单个/批量判断是否为空
if (args == null || args.length == 0)
return false;
for (String arg : args) {
if (null == arg || arg.trim().length() == 0 || "null".equals(arg)) {
return false;
}
}
return true;
}

/**
* Description :去掉str中所有的tar
*
* @author : ChenBin
* @date : 2016-6-17 上午11:40:03
*/
public static String removeAll(String str, String tar) {
if (compareTrim(str))
return str.replaceAll(tar, EMPTY_STR);
return "";
}

/**
* Description : 移除字符串中的空格
*
* @author : ChenBin
* @date : 2017年1月4日 下午5:26:13
*/
public static String removeEmpty(String str) {
if (compareTrim(str))
return removeAll(str, SPACING);
return null;
}

/**
* Description :将字符串转换成Integer类型
*
* @author : ChenBin
* @date : 2016-6-17 上午11:39:17
*/
public static int strToInteger(String arg) {
String s = removeAll(arg, SPACING);
if (compareTrim(s))
if (isInt(s))
return Integer.parseInt(s);
return 0;
}

/**
* Description :将字符串转换成Integer类型
*
* @author : ChenBin
* @date : 2016-6-17 上午11:39:17
*/
public static long strToLong(String arg) {
String s = removeAll(arg, SPACING);
if (compareTrim(s))
if (isInt(s))
return Long.parseLong(s);
return 0L;
}

/**
* @author : ChenBin
* @date : 2015-1-27 上午10:12:22
* @return 相等返回true,否则返回false
*/
public static boolean equals(String s1, String s2) {
if (compareTrim(s1, s2) && s1.equals(s2))
return true;
if ((null == s1 && null == s2) || ("".equals(s1) && "".equals(s2)))
return true;
return false;
}

/**
* Description : 判断字符串是否符合电子邮件格式
*
* @author : ChenBin
* @date : 2016-3-9 下午4:11:45
*/
public static boolean isEmail(String email) {
if (!StringUtils.compareTrim(email))
return false;
return email.matches(REGEX_EMAIL);
}

/**
* Description :判断是否为浮点数或者整数
*
* @author : ChenBin
* @date : 2016-3-9 下午4:27:54
*/
public static boolean isNumber(String num) {
if (!StringUtils.compareTrim(num))
return false;
Matcher isNum = Pattern.compile(REGEX_NUMBER).matcher(num);
if (!isNum.matches())
return false;
return true;
}

/**
* Description :严格判断字符串是否为合法手机号 11位 13 14 15 18开头
*
* @author : ChenBin
* @date : 2016-3-9 下午4:29:40
*/
public static boolean isMobile(String mobile) {
if (!StringUtils.compareTrim(mobile))
return false;
return mobile.matches(REGEX_MOBILE);
}

/**
* Description : 判断字符串是否为纯数字
*
* @author : ChenBin
* @date : 2016-3-9 下午4:34:45
*/
public static boolean isInt(String num) {
if (!StringUtils.compareTrim(num))
return false;
return num.matches(REGEX_INT);
}

/**
* Description :验证是否为符合只包含数字、字母、下划线的用户名
*
* @author : ChenBin
* @date : 2016-3-9 下午4:54:35
*/
public static boolean isUsername(String username) {
if (!StringUtils.compareTrim(username))
return false;
return username.matches(REGEX_USERNAME);
}

/**
* Description :验证是否为符合只包含数字、字母、下划线且长度在min与max之间(含)的用户名
*
* @author : ChenBin
* @date : 2016-3-9 下午5:13:17
*/
public static boolean checkUsername(String username, int min, int max) {
if (min > max || min < 1 || max < 1)
return false;
logger.error("不正确的长度限制-->min=" + min + ",max=" + max + ";匹配错误规则:min > max || min < 1 || max < 1");
if (!isUsername(username))
return false;
int len = username.length();
return len >= min && len <= max;
}

/**
* @author : ChenBin
* @date : 2015-3-9 上午10:48:54
* @Description :将字符串转换为大写字母
*/
public static String upperCase(String str) {
if (compareTrim(str))
return str.toUpperCase();
return str;
}

/**
* @author : ChenBin
* @date : 2015-3-9 上午10:50:35
* @Description :将字符串转换为小写字母
*/
public static String lowerCase(String str) {
if (compareTrim(str))
return str.toLowerCase();
return str;
}

/**
* Description : 将字符串str按照regex分割,并转换成数组
*
* @author : ChenBin
* @date : 2016年12月23日 下午5:41:34
*/
public static String[] strToStrings(String str, String regex) {
if (compareTrim(str) && !",".equals(str))
return str.split(regex);

return new String[0];
}

/**
* Description : 判断Object 或者 String 是否为null 待完善
*
* @author wangzhiyuan
* @param object
* @return
*/
public static boolean isEmpty(Object o ){
if(o == null){
return true;
}else if(o.toString() == null || o.toString().isEmpty() || o.toString().equals("") || "" == o.toString() || o.toString().length() <1 ){
return true;
}
return false;
}

/***
* Description 数字转为长度为tag的字符串,不足前面填0
* @author wangzhiyuan
* @date 2017-11-4 下午2:52:22
* @param val
* @param tag 位数
* @return String
*/
public static String longToString(Long val,Integer tag){
if(val != null && val.toString().length() < tag){
int length = val.toString().length();
String temp = "";
for(int i =0; i< tag-length;i++){
temp+="0";
}
return temp+val;
}
return val+"";
}
/**
*
* Description 字符串转为泛型集合
* @author wangzhiyuan
* @date 2017-11-21 上午10:37:20
* @param str
* @param tag
* @return List<String>

*/
public static List<String> StrToArrayList(String str,String tag){
List<String> result = new ArrayList<String>();
if(StringUtils.isEmpty(tag) || StringUtils.isEmpty(str)){
return result;
}
String[] strs = str.split(tag);
for(String temp:strs){
if(!StringUtils.isEmpty(tag)){
result.add(temp.trim());
}
}
return result;
}

/**
* 循环遍历list 比较list中的对象field值是否跟Comparison一致,如有,则返回true
* @param list 遍历对象
* @param field 对象中的属性
* @param Comparison 比较值
* @return
* @throws Exception
*/
public static boolean isContain(List<?> list, String field , Object Comparison) throws Exception{
for(Object o :list){
Method method = o.getClass().getMethod("get"+field, new Class[]{});
Object value = method.invoke(o, new Object[]{});
if(value.equals(Comparison)){
return true;
}
}
return false;
}


// public static void main(String[] args) throws SecurityException, IllegalArgumentException, NoSuchMethodException, IllegalAccessException, InvocationTargetException {
// List<LgtPzfcPathwayNptDetails> lppNpts = new ArrayList<LgtPzfcPathwayNptDetails>();
// LgtPzfcPathwayNptDetails l1 = new LgtPzfcPathwayNptDetails();
// l1.setArriveStatus(10);
// l1.setNptPk(Long.valueOf(103));
// lppNpts.add(l1);
//
// LgtPzfcPathwayNptDetails l2 = new LgtPzfcPathwayNptDetails();
// l2.setArriveStatus(20);
// l2.setNptPk(Long.valueOf(104));
// lppNpts.add(l2);
//
// isContain(lppNpts, "NptPk", "103");
// }


//
// @SuppressWarnings("unchecked")
// public static Map<String, Object> getMapByCreditJson(String json) {
// Map<String, Object> resultMap = new HashMap<String,Object>();
// if(json != null && !"".equals(json.trim())){
// if(json.substring(0, 1).equals("[")){
// json = json.substring(1,json.length()-1);
// }
// //先解析json第一层
// ObjectMapper objectMapper = new ObjectMapper();
// try {
// resultMap = objectMapper.readValue(json, Map.class);
// } catch (Exception e){
// System.out.println("[getMapByCreditJson]------解析json成Map失败"+e.getMessage().toString());
// }
// return resultMap;
// }else{
// return resultMap;
// }
//
// }
//
// /** 把json字符串解析为Map对象
// * @param json
// * @return
// * @throws IOException
// * @throws JsonMappingException
// * @throws JsonParseException
// * @throws Exception
// */
// @SuppressWarnings("unchecked")
// public static Map<String, Object> parseJsonToMap(String json) throws JsonParseException, JsonMappingException, IOException{
// Map<String, Object> resultMap = new HashMap<String, Object>();
// if (StringUtils.isEmpty(json)) {
// if (json.substring(0, 1).equals("[")) {
// json = json.substring(1, json.length() - 1);
// }
// ObjectMapper objectMapper = new ObjectMapper();
// resultMap = objectMapper.readValue(json, Map.class);
// }
// return resultMap;
// }



/**
* 文本转为字符串
* wangzhiyuan
* @param filePath 文本存放路径
* @date 2017-11-21
* @return
*/
public static String readTxtFileWidthEncode(String filePath,String encoding){
String json = "";
StringBuffer sb = new StringBuffer();
try {
File file=new File(filePath);
if(file.isFile() && file.exists()){
InputStreamReader read = new InputStreamReader(
new FileInputStream(file),encoding);
BufferedReader bufferedReader = new BufferedReader(read);
String lineTxt = null;
while((lineTxt = bufferedReader.readLine()) != null){
sb.append(lineTxt);
}
read.close();
}else{
System.out.println("找不到指定的文件");
}
} catch (Exception e) {
System.out.println("读取文件内容出错");
e.printStackTrace();
}
json = sb.toString().trim();
System.out.println(json);
return json;
}

}

posted @ 2018-01-19 11:07  小任猿  阅读(169)  评论(0编辑  收藏  举报