STRING公共方法


import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import javax.servlet.ServletContext;




/**
 * 字符串操作类<p>
 * 包含功能:编码转换;HTML标记处理
 * <p>
 */
public class StringUtil {

/**将Double转换为String不以科学记数法表示
* @param d
* @return String
*/
public static String DoubleToString(Double d){
NumberFormat formatter = new DecimalFormat("#.######"); 
return formatter.format(d); 
}

/**将类型Object转换为String,Object为空或异常时返还"";
* @param o
* @return String
*/
public static String ObjectToString(Object o){
try{
if (o != null){
return o.toString();

}else{
return "";
}
}catch(Exception e){
return "";
}
}
/**将类型String转换为String,String为空或异常时返还0;
* @param o
* @return String
*/
public static String StringToString(Object o){
try{
if (o != null){
return o.toString();

}else{
return "0";
}
}catch(Exception e){
return "0";
}
}
/**将类型Object转换为date,Object为空或异常时返还"";
* @param o
* @return Date
*/
public static Date ObjectToDate(Object o){
try{
if (o != null){
String s=ObjectToString(o);
return DateTimeUtil.stringToDate(s, "yyyy-MM-dd");

}else{
//return new java.util.Date();
return null;
}
}catch(Exception e){
return new java.util.Date();
}
}
/**将类型Object转换为date,Object为空或异常时返还"";
* @param o
* @return Date
*/
public static Date ObjectToDate2(Object o){
try{
if (o != null){
String s=ObjectToString(o); 
return DateTimeUtil.stringToDate(s, "yyyy-MM-dd hh:mm:ss");

}else{
return new java.util.Date();
}
}catch(Exception e){
return new java.util.Date();
}
}
/**将类型Object转换为Double,Object为空或异常时返还0;
* @param o
* @return Double
*/
public static Double ObjectToDouble(Object o){
try{
if (o != null){
return Double.parseDouble(o.toString());

}else{
return 0d;
}
}catch(Exception e){
return 0d;
}
}
/**将类型Object转换为Integer,Object为空或异常时返还0;
* @param o
* @return Integer
*/
public static Integer ObjectToInteger(Object o){
try{
if (o != null){
return Integer.parseInt(o.toString());

}else{
return 0;
}
}catch(Exception e){
return 0;
}
}
/**将类型Object转换为Long,Object为空或异常时返还0;
* @param o
* @return Long
*/
public static Long ObjectToLong(Object o){
try{
if (o != null){
return Long.parseLong(o.toString());

}else{
return 0l;
}
}catch(Exception e){
return 0l;
}
}

/**
* 将给定的字符串转换为中文GBK编码的字符串;若为NULL,转换成空 ("")
*
* @param str 输入字符串
* @return 经GBK编码后的字符串,如果有异常,则返回原编码字符串
*/
public static String toChinese(final String str) {
if (isNullorBlank(str)) {
return "";
}
String rn = str;
try {
rn = new String(str.getBytes("ISO8859_1"), "GBK");
}
catch (Exception e) {
//log...
}
return rn.trim();
} //end toGb2312()


/**
* 将给定的中文GBK字符串转换为ISO编码的字符串;若为NULL,转换成空 ("")
*
* @param str 输入字符串
* @return 经GBK编码后的字符串,如果有异常,则返回原编码字符串
*/
public static String toIso(final String str) {
if (isNullorBlank(str)) {
return "";
}
String rn = str;
try {
rn = new String(str.getBytes("GBK"), "ISO8859_1");
}
catch (Exception e) {
//log...
}
return rn.trim();
} //end toGb2312()


/**
* 判断给定字符串是否为空
*
* @param str 需要检查的字符串
* @return boolean 如果为null或"",则返回true,否则为false
*/
public static boolean isNullorBlank(final String str) {
boolean isNorB = false;
if (null == str || 0 >= str.length()) {
isNorB = true;
}
return isNorB;
} //end isNullorBlank()


/**
* 返回字符串,若是NULL返回""
*
* @param str 需要检查的字符串
* @return 若是NULL返回""
*/
public static String escapeNull(final String str) {
if (isNullorBlank(str)) {
return "";
}
return str;
} //end isNullorBlank()


/**
* 忽略HTML标记。
* <p>
*将尖括号、引号、连接号等用转义符替换。
*
* @param input 需要检查的字符串
* @return 转化后的字串
*/
public static String escapeHtmlTags(final String input) {
if (isNullorBlank(input)) {
return input;
}
StringBuffer buf = new StringBuffer();
char ch = ' ';
for (int i = 0; i < input.length(); i++) {
ch = input.charAt(i);
if (ch == '<') {
buf.append("&lt;");
}
else if (ch == '>') {
buf.append("&gt;");
}
else if (ch == '&') {
buf.append("&amp;");
}
else if (ch == '"') {
buf.append("&quot;");
}
else if (ch == '\n') {
buf.append("<br>");
}
else if (ch == '\'') {
buf.append("&acute;");
}
else if (ch == ' ') {
buf.append("&nbsp;");
}
else {
buf.append(ch);
}
}
return buf.toString();
} //end escapteHtmlTags()


/**
* 替换退格、换行符为<br>。
*
* @param input 操作字串
* @return 替换后的字串,所有退格、换行符都转成<BR/>
*/
public static String convertNewLines(String input) {
input = replace(input, "\r\n", "\n");
input = replace(input, "\n", "<BR/>");
return input;
} //end convertNewLines()


/**
* 使用给定的字串替换源字符串中指定的字串。
*
* @param mainString 源字符串
* @param oldString 被替换的字串
* @param newString 替换字串
* @return String
*/
public static String replace(final String mainString, final String oldString,
final String newString) {
if (mainString == null) {
return null;
}
int i = mainString.lastIndexOf(oldString);
if (i < 0) {
return mainString;
}
StringBuffer mainSb = new StringBuffer(mainString);
while (i >= 0) {
mainSb.replace(i, i + oldString.length(), newString);
i = mainString.lastIndexOf(oldString, i - 1);
}
return mainSb.toString();
}


/**
* 取给定分隔符间的子串。
* <p>
* <TYPE>.<FROM>.<DESCRIPTON> such as: ERROR.LOGIN.NO_SUCHUSER.
* @param srcStr 源字串
* @param ch 分隔符
* @return 俩分隔符间的子串。若只有一个分隔符,则返回后半部分,若无分隔符号,则返回""。
*/
public static String getSubStr(final String srcStr, final char ch) {
String resultStr = "";
//the first '.' index
int beginIndex = srcStr.indexOf(ch);
if (0 < beginIndex) {
beginIndex++;
//the end '.' index
int endIndex = srcStr.indexOf(ch, beginIndex);
//if only one '.' then get the string length
if (0 >= endIndex) {
endIndex = srcStr.length();
}
//get the substring as requestFrom
resultStr = srcStr.substring(beginIndex, endIndex);
}
return resultStr;
} //end getSubStr()


/**
* convert string to int
* @param  StringNum
* @return int if it can be converted retrun intNum,or return 0
*/
public static int toInt(String StringNum) {
try {
return Integer.parseInt(StringNum);
}
catch (Exception e) {
return 0;
}
} //end toInt()

/**
* 将字符串转换为整数。
* @param toParse 待转换的字符串。
* @param defaultValue 默认值。
* @return 转换后的整数;如果转换时抛出异常,返回默认值。
*/
public static int parseInt(String toParse, int defaultValue) {
if (toParse == null)
return defaultValue;
try {
return Integer.parseInt(toParse);
} catch (Exception ex) {
return defaultValue;
}
}


/**
* 用户名是否合法。
*
* @param userName 用户名
* @return 合法:true,否则:false
*/
public static boolean isValidUserName(final String userName) {
String namePattern = "^[a-zA-Z0-9_\\-\\.]{3,}$";
Pattern p = Pattern.compile(namePattern);
Matcher m = p.matcher(userName);
return m.find();
} //end isValidUserName


/**
* 邮件地址是否合法。
*
* @param mailAddr
* @return boolean
*/
public static boolean isValidMailAddr(final String mailAddr) {
//email pattern
String emailPattern =
"^[a-zA-Z0-9_\\-]{1,}@[a-zA-Z0-9_\\-]{1,}\\.[a-zA-Z0-9_\\-.]{1,}$";
Pattern p = Pattern.compile(emailPattern);
Matcher m = p.matcher(mailAddr);
return m.find();
} //end isValidMailAddr


/**
* 文件名是否合法。
*
* @param fileName 用户名
* @return boolean 合法:true,否则:false
*/
public static boolean isValidFileName(final String fileName) {
String filePattern = "^[a-zA-Z0-9_\\-\\.]{3,}$";
Pattern p = Pattern.compile(filePattern);
Matcher m = p.matcher(fileName);
return m.find();
} //end isValidFileName



public static boolean isOfficeDoc(final String extName) {
String filePattern = "(doc)|(docx)|(xls)|(xlsx)|(ppt)|(pptx)";
Pattern p = Pattern.compile(filePattern,Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(extName);
return m.find();
} //end isValidFileName


/**
* 是否为允许类型文件
*
* @param fileName 文件名
* @param fileType 允许类型
* @return boolean 合法:true,否则:falise
*/
public static boolean isPermitFile(final String fileName, Collection fileType) {
try {
//boolean includeChinese = isValidFileName(fileName);
boolean permit = false;
String thisFileType = fileName.substring(fileName.length() - 3,
fileName.length());
Iterator ite = fileType.iterator();
while (ite.hasNext()) {
if ( ( (String) ite.next()).equals(thisFileType)) {
permit = true;
}
} //end while
//return includeChinese&&permit;
return permit;
} //end try...
catch (Exception ex) {
return false;
} //end catch...
}


/**
* 获取文件的类型
*
* @param fileName 文件名
* @return fileType 文件类型
*/
public static String getFileType(final String fileName) {
//return fileName.substring(fileName.indexOf(".")+1,fileName.length());
return fileName.substring(fileName.length() - 3, fileName.length());
}


/**
* 判断字符串是否为null或NULL或"",若是上述字符串则改其值为&nbsp;
* (主要用于处理页面中获取数据,清洁界面)
* @param str String
* @return String
*/
public static String convertNullString(String str){
if (str == null || str.equals("null") || str.equals("NULL") || str.equals("")) {
str = "";
}
return str;
}


/**
* 把一个字符串转换为可以在SQL语句中使用的字符串。<br/>
* 将传入的字符串中的单引号替换为两个单引号,并在两端加单引号。
* @param original 要转换的字符串
* @return 转换后可直接用于拼接SQL语句的字符串
*/
public static String toSQLString(String original) {
if (original == null || original.length() < 1)
return "''";
return "'" + original.replaceAll("'", "''") + "'";
}

/**
* 向一个StringBuilder后面附加一个SQL或者HQL子句。
* @param builder 要附加到的StringBuilder实例。不能是null。
* @param op 操作符,可以是and或者or,不能是between、not、like等。
* @param clause 要附加的子句,必须是逻辑表达式。
* @throws NullPointerException 传入的builder是null。
*/
public static final void appendClause(StringBuilder builder,
String op, String clause) {
if (builder.length() > 0) {
builder.append(' ');
builder.append(op);
builder.append(' ');
}
builder.append('(');
builder.append(clause);
builder.append(')');
}

public static final boolean isEmpty(String toTest) {
return toTest == null || toTest.trim().length() < 1;
}


/**
* 在一个字符串两端加上百分号(%),并转换为SQL中适用的字符串。
* @param original 原始字符串。
* @return 适用于模糊查询的字符串。
*/
public static String toFuzzySqlString(String original) {
return toSQLString("%" + original + "%");
}

private static final char[] HEX_CHARS = {'0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

public static final String shortToHex(short val) {
StringBuilder builder = new StringBuilder(4);
for (int i = 0; i < 4; i ++) {
builder.append(HEX_CHARS[(val >> ((3 - i) * 4)) & 15]);
}
return builder.toString();
}

public static final short hexToShort(String hex) {
short val = 0;
if (hex == null || hex.length() != 4) return val;
for (int i = 0; i < 4; i ++) {
short h = hexIndexOf(hex.charAt(i));
val = (short)((val << 4) | h);
}
return val;
}

private static final short hexIndexOf(char ch) {
for (int i = 0; i < HEX_CHARS.length; i ++) {
if (ch == HEX_CHARS[i])
return (short)i;
}
return 0;
}
/**
* 把一个字符串转换为可以纯文字的字符串。<br/>
* @param str 要转换的字符串
* @return 转换后可直接按传入需要截取字符串的长度截取字符串
*/
public static String toTextString(String str,int len) {
if (str == null || str.length() < 1)
return "''";
while (str.indexOf("<") != -1){
str=str.replace(str.substring(str.indexOf("<"), str.indexOf(">")+1),"");
}
str=str.replace("&nbsp;", "");
str=str.substring(0, str.length()<len?str.length():len);
return str;

/**
* 把一个字符串过滤出特殊字符<br/>
* @param str 要过滤的字符串
* @return 过滤后字符串
*/
public static String toFilterString(String str) {
if (str == null || str.length() < 1)
return "";
str=str.toLowerCase();
str=str.replace("delete", "");
str=str.replace("update", "");
str=str.replace("insert", "");
str=str.replace("select", "");
str=str.replace("or", "");
str=str.replace("and", "");
str=str.replace("having", "");
str=str.replace("order", "");
str=str.replace("by", "");
str=str.replace("group", "");
str=str.replace("where", "");
str=str.replace("from", "");
str=str.replace("%", "");
str=str.replace("|", "");
str=str.replace("&", "");
str=str.replace(";", "");
str=str.replace("$", "");
str=str.replace("@", "");
str=str.replace("'", "");
str=str.replace("\"", "");
str=str.replace("\'", "");
str=str.replace("<", "");
str=str.replace(">", "");
str=str.replace("CR", "");
str=str.replace("LF", "");
str=str.replace("=", "");
// str=str.replace(",", "");
str=str.replace("BS", "");
str=str.replace("\\", "");
str=str.replace("(", "");
str=str.replace(")", "");
str=str.replace("+", "");
return str.trim();
}


/**
* 去掉不可见字符。
* @param str
* @return
*/
public static String replaceNotVisable(String str){
char[] ary=str.toCharArray();
List<Character> list=new ArrayList<Character>();
for(int i=0;i<ary.length;i++){
int c=(int)ary[i];
if(isNotViable(c))
continue;
list.add((char)c);
}
Object[] aryc=(Object[]) list.toArray();
char[] arycc=new char[aryc.length];
for(int i=0;i<aryc.length;i++){
arycc[i]=(Character) aryc[i];
}
String out=new String(arycc);
return out;
}

private static boolean isNotViable(int i){
if((i>=1 && i<=8) || (i>=11 && i<=12) ||  (i>=14 && i<=27) ||  (i>=129 && i<=254))
return true;
return false;
}

}  
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值