java 转义工具_Java字符转换转义的工具类

}

//转换为html

title/Alt属性文本,主要转换&,单引号和双引号字符

public static String encode4Title(String value) {

return notNull(value).replaceAll("&",

"&").replaceAll("'",

"'")

.replaceAll(""", """);

}

public static String escape4Sql(String value){

value = notNull(value);

if(value.equals(""))return "";

StringBuffer buffer = new StringBuffer();

if(value.length() > 15)value = value.substring(0,

15);

for (int i = 0; i < value.length(); i++) {

char ch = value.charAt(i);

if(ch == '[')buffer.append("[[]");

else if(ch=='\'')buffer.append("''");

else if(ch=='%')buffer.append("[%]");

else if(ch=='_')buffer.append("[_]");

else if(ch=='^')buffer.append("[^]");

else buffer.append(ch);

}

return buffer.toString();

}

public static String encode4Html(String value) {

value = notNull(value);

if(value.equals(""))return "";

StringBuffer result = new StringBuffer();

for (int i = 0; i < value.length(); i++) {

char ch = value.charAt(i);

if (ch == '

result.append("<");

else if (ch == '&')

result.append("&");

else if (ch == '"')

result.append(""");

else if (ch == '\r')

result.append("
");

else if (ch == '\n') {

if (value.charAt(i - 1) == '\r') {

} else

result.append("
");

} else if (ch == '\t')

result.append("   &nbsp");

else if (ch == ' ')

result.append(" ");

else

result.append(ch);

}

return result.toString();

}

//转换非空对象,防止产生NullPointerException异常

public static String notNull(Object s) {

if (s instanceof String) {

if (s == null || s.toString().trim().equals("")) {

return "";

} else {

return s.toString().trim();

}

} else if (s instanceof Integer) {

if (s == null) {

return "";

} else {

return s.toString();

}

} else {

return "";

}

}

public static String strChinese(String a) {

try {

return new String(a.getBytes("iso-8859-1"));

} catch (UnsupportedEncodingException ex) {

return "";

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值