java常用工具類 Reflect反射工具類、String字符串工具類
本文實(shí)例為大家分享了java常用工具類的具體代碼,供大家參考,具體內(nèi)容如下
Reflect反射工具類
package com.jarvis.base.util;
/**
*
*
* @Title: ReflectHelper.java
* @Package com.jarvis.base.util
* @Description: 反射工具類
* @version V1.0
*/
public class ReflectHelper {
/**
* 提指定的類載入以系統(tǒng)中
*
* @param name
* 類名稱
* @return 類對(duì)象
* @throws ClassNotFoundException
*/
public static Class<?> classForName(String name) throws ClassNotFoundException {
try {
return Thread.currentThread().getContextClassLoader().loadClass(name);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
System.err.println("類[" + name + "]加載出錯(cuò)");
} catch (SecurityException e) {
e.printStackTrace();
System.err.println("類[" + name + "]加載出錯(cuò)");
}
return Class.forName(name);
}
/**
* 根據(jù)名稱生成指定的對(duì)象
*
* @param name
* 類名稱
* @return 具體的對(duì)象,若發(fā)生異常,則返回null
*/
public static Object objectForName(String name) {
try {
return Class.forName(name).newInstance();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("類[" + name + "]獲取對(duì)象實(shí)例出錯(cuò)");
}
return null;
}
}
String字符串工具類
package com.jarvis.base.util;
import java.io.UnsupportedEncodingException;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.StringTokenizer;
import java.util.UUID;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
*
*
* @Title: StringHelper.java
* @Package com.jarvis.base.utils
* @Description:
* @version V1.0 字符串處理工具類。
*/
public final class StringHelper {
/**
* 描述: 構(gòu)造方法
*/
private StringHelper() {
}
/**
* 空字符串
*/
public static final String EMPTY_STRING = "";
/**
* 點(diǎn)
*/
public static final char DOT = '.';
/**
* 下劃線
*/
public static final char UNDERSCORE = '_';
/**
* 逗點(diǎn)及空格
*/
public static final String COMMA_SPACE = ", ";
/**
* 逗點(diǎn)
*/
public static final String COMMA = ",";
/**
* 開(kāi)始括號(hào)
*/
public static final String OPEN_PAREN = "(";
/**
* 結(jié)束括號(hào)
*/
public static final String CLOSE_PAREN = ")";
/**
* 單引號(hào)
*/
public static final char SINGLE_QUOTE = '\'';
/**
* 回車
*/
public static final String CRLF = "\r\n";
/**
* 常量 12
*/
public static final int FIANL_TWELVE = 12;
/**
* 十六進(jìn)制常量 0x80
*/
public static final int HEX_80 = 0x80;
/**
* 十六進(jìn)制常量 0xff
*/
public static final int HEX_FF = 0xff;
/**
* 把字符數(shù)組,轉(zhuǎn)化為一個(gè)字符
*
* @param seperator
* 字符分隔符
* @param strings
* 數(shù)組對(duì)象
* @return 字符串
*/
public static String join(String seperator, String[] strings) {
int length = strings.length;
if (length == 0) {
return EMPTY_STRING;
}
StringBuffer buf = new StringBuffer(length * strings[0].length()).append(strings[0]);
for (int i = 1; i < length; i++) {
buf.append(seperator).append(strings[i]);
}
return buf.toString();
}
/**
* 把迭代對(duì)象轉(zhuǎn)化為一個(gè)字符串
*
* @param seperator
* 分隔符
* @param objects
* 迭代器對(duì)象
* @return 字符串
*/
public static String join(String seperator, Iterator<?> objects) {
StringBuffer buf = new StringBuffer();
if (objects.hasNext()) {
buf.append(objects.next());
}
while (objects.hasNext()) {
buf.append(seperator).append(objects.next());
}
return buf.toString();
}
/**
* 把兩個(gè)字符串?dāng)?shù)組的元素用分隔符連接,生成新的數(shù)組,生成的數(shù)組以第一個(gè)字符串?dāng)?shù)組為參照,與其長(zhǎng)度相同。
*
* @param x
* 字符串?dāng)?shù)組
* @param seperator
* 分隔符
* @param y
* 字符串?dāng)?shù)組
* @return 組合后的字符串?dāng)?shù)組
*/
public static String[] add(String[] x, String seperator, String[] y) {
String[] result = new String[x.length];
for (int i = 0; i < x.length; i++) {
result[i] = x[i] + seperator + y[i];
}
return result;
}
/**
* 生成一個(gè)重復(fù)的字符串,如需要重復(fù)*10次,則生成:**********。
*
* @param string
* 重復(fù)元素
* @param times
* 重復(fù)次數(shù)
* @return 生成后的字符串
*/
public static String repeat(String string, int times) {
StringBuffer buf = new StringBuffer(string.length() * times);
for (int i = 0; i < times; i++) {
buf.append(string);
}
return buf.toString();
}
/**
* 字符串替換處理,把舊的字符串替換為新的字符串,主要是通過(guò)字符串查找進(jìn)行處理
*
* @param source
* 需要進(jìn)行替換的字符串
* @param old
* 需要進(jìn)行替換的字符串
* @param replace
* 替換成的字符串
* @return 替換處理后的字符串
*/
public static String replace(String source, String old, String replace) {
StringBuffer output = new StringBuffer();
int sourceLen = source.length();
int oldLen = old.length();
int posStart = 0;
int pos;
// 通過(guò)截取字符串的方式,替換字符串
while ((pos = source.indexOf(old, posStart)) >= 0) {
output.append(source.substring(posStart, pos));
output.append(replace);
posStart = pos + oldLen;
}
// 如果還有沒(méi)有處理的字符串,則都添加到新字符串后面
if (posStart < sourceLen) {
output.append(source.substring(posStart));
}
return output.toString();
}
/**
* 替換字符,如果指定進(jìn)行全替換,必須設(shè)wholeWords=true,否則只替換最后出現(xiàn)的字符。
*
* @param template
* 字符模板
* @param placeholder
* 需要替換的字符
* @param replacement
* 新的字符
* @param wholeWords
* 是否需要全替換,true為需要,false為不需要。如果不需要,則只替換最后出現(xiàn)的字符。
* @return 替換后的新字符
*/
public static String replace(String template, String placeholder, String replacement, boolean wholeWords) {
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
final boolean actuallyReplace = wholeWords || loc + placeholder.length() == template.length()
|| !Character.isJavaIdentifierPart(template.charAt(loc + placeholder.length()));
String actualReplacement = actuallyReplace ? replacement : placeholder;
return new StringBuffer(template.substring(0, loc)).append(actualReplacement).append(
replace(template.substring(loc + placeholder.length()), placeholder, replacement, wholeWords))
.toString();
}
}
/**
* 替換字符,只替換第一次出現(xiàn)的字符串。
*
* @param template
* 字符模板
* @param placeholder
* 需要替換的字符串
* @param replacement
* 新字符串
* @return 替換后的字符串
*/
public static String replaceOnce(String template, String placeholder, String replacement) {
int loc = template.indexOf(placeholder);
if (loc < 0) {
return template;
} else {
return new StringBuffer(template.substring(0, loc)).append(replacement)
.append(template.substring(loc + placeholder.length())).toString();
}
}
/**
* 把字符串,按指字的分隔符分隔為字符串?dāng)?shù)組
*
* @param seperators
* 分隔符
* @param list
* 字符串
* @return 字符串?dāng)?shù)組
*/
public static String[] split(String list, String seperators) {
return split(list, seperators, false);
}
/**
* 把字符串,按指字的分隔符分隔為字符串?dāng)?shù)組
*
* @param seperators
* 分隔符
* @param list
* 字符串
* @param include
* 是否需要把分隔符也返回
* @return 字符串?dāng)?shù)組
*/
public static String[] split(String list, String seperators, boolean include) {
StringTokenizer tokens = new StringTokenizer(list, seperators, include);
String[] result = new String[tokens.countTokens()];
int i = 0;
while (tokens.hasMoreTokens()) {
result[i++] = tokens.nextToken();
}
return result;
}
/**
* 提取字符串中,以.為分隔符后的所有字符,如string.exe,將返回exe。
*
* @param qualifiedName
* 字符串
* @return 提取后的字符串
*/
public static String unqualify(String qualifiedName) {
return unqualify(qualifiedName, ".");
}
/**
* 提取字符串中,以指定分隔符后的所有字符,如string.exe,將返回exe。
*
* @param qualifiedName
* 字符串
* @param seperator
* 分隔符
* @return 提取后的字符串
*/
public static String unqualify(String qualifiedName, String seperator) {
return qualifiedName.substring(qualifiedName.lastIndexOf(seperator) + 1);
}
/**
* 提取字符串中,以.為分隔符以前的字符,如string.exe,則返回string
*
* @param qualifiedName
* 字符串
* @return 提取后的字符串
*/
public static String qualifier(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
if (loc < 0) {
return EMPTY_STRING;
} else {
return qualifiedName.substring(0, loc);
}
}
/**
* 向字符串?dāng)?shù)組中的所有元素添加上后綴
*
* @param columns
* 字符串?dāng)?shù)組
* @param suffix
* 后綴
* @return 添加后綴后的數(shù)組
*/
public static String[] suffix(String[] columns, String suffix) {
if (suffix == null) {
return columns;
}
String[] qualified = new String[columns.length];
for (int i = 0; i < columns.length; i++) {
qualified[i] = suffix(columns[i], suffix);
}
return qualified;
}
/**
* 向字符串加上后綴
*
* @param name
* 需要添加后綴的字符串
* @param suffix
* 后綴
* @return 添加后綴的字符串
*/
public static String suffix(String name, String suffix) {
return (suffix == null) ? name : name + suffix;
}
/**
* 向字符串?dāng)?shù)組中的所有元素,添加上前綴
*
* @param columns
* 需要添加前綴的字符串?dāng)?shù)組
* @param prefix
* prefix
* @return
*/
public static String[] prefix(String[] columns, String prefix) {
if (prefix == null) {
return columns;
}
String[] qualified = new String[columns.length];
for (int i = 0; i < columns.length; i++) {
qualified[i] = prefix + columns[i];
}
return qualified;
}
/**
* 向字符串添加上前綴
*
* @param name
* 需要添加前綴的字符串
* @param prefix
* 前綴
* @return 添加前綴后的字符串
*/
public static String prefix(String name, String prefix) {
return (prefix == null) ? name : prefix + name;
}
/**
* 判斷字符串是否為"true"、"t",如果是,返回true,否則返回false
*
* @param tfString
* 需要進(jìn)行判斷真/假的字符串
* @return true/false
*/
public static boolean booleanValue(String tfString) {
String trimmed = tfString.trim().toLowerCase();
return trimmed.equals("true") || trimmed.equals("t");
}
/**
* 把對(duì)象數(shù)組轉(zhuǎn)化為字符串
*
* @param array
* 對(duì)象數(shù)組
* @return 字符串
*/
public static String toString(Object[] array) {
int len = array.length;
if (len == 0) {
return StringHelper.EMPTY_STRING;
}
StringBuffer buf = new StringBuffer(len * FIANL_TWELVE);
for (int i = 0; i < len - 1; i++) {
buf.append(array[i]).append(StringHelper.COMMA_SPACE);
}
return buf.append(array[len - 1]).toString();
}
/**
* 描述:把數(shù)組中的所有元素出現(xiàn)的字符串進(jìn)行替換,把舊字符串替換為新字符數(shù)組的所有元素,只替換第一次出現(xiàn)的字符。
*
* @param string
* 需要替換的數(shù)組
* @param placeholders
* 需要替換的字符串
* @param replacements
* 新字符串?dāng)?shù)組
* @return 替換后的字符串?dāng)?shù)組
*/
public static String[] multiply(String string, Iterator<?> placeholders, Iterator<?> replacements) {
String[] result = new String[] { string };
while (placeholders.hasNext()) {
result = multiply(result, (String) placeholders.next(), (String[]) replacements.next());
}
return result;
}
/**
* 把數(shù)組中的所有元素出現(xiàn)的字符串進(jìn)行替換,把舊字符串替換為新字符數(shù)組的所有元素,只替換第一次出現(xiàn)的字符。
*
* @param strings
* 需要替換的數(shù)組
* @param placeholder
* 需要替換的字符串
* @param replacements
* 新字符串?dāng)?shù)組
* @return 替換后的字符串?dāng)?shù)組
*/
private static String[] multiply(String[] strings, String placeholder, String[] replacements) {
String[] results = new String[replacements.length * strings.length];
int n = 0;
for (int i = 0; i < replacements.length; i++) {
for (int j = 0; j < strings.length; j++) {
results[n++] = replaceOnce(strings[j], placeholder, replacements[i]);
}
}
return results;
}
/**
* 統(tǒng)計(jì)Char在字符串中出現(xiàn)在次數(shù),如"s"在字符串"string"中出現(xiàn)的次數(shù)
*
* @param string
* 字符串
* @param character
* 需要進(jìn)行統(tǒng)計(jì)的char
* @return 數(shù)量
*/
public static int count(String string, char character) {
int n = 0;
for (int i = 0; i < string.length(); i++) {
if (string.charAt(i) == character) {
n++;
}
}
return n;
}
/**
* 描述:計(jì)算字符串中未引用的字符
*
* @param string
* 字符串
* @param character
* 字符
* @return 未引用的字符數(shù)
*/
public static int countUnquoted(String string, char character) {
if (SINGLE_QUOTE == character) {
throw new IllegalArgumentException("Unquoted count of quotes is invalid");
}
int count = 0;
int stringLength = string == null ? 0 : string.length();
boolean inQuote = false;
for (int indx = 0; indx < stringLength; indx++) {
if (inQuote) {
if (SINGLE_QUOTE == string.charAt(indx)) {
inQuote = false;
}
} else if (SINGLE_QUOTE == string.charAt(indx)) {
inQuote = true;
} else if (string.charAt(indx) == character) {
count++;
}
}
return count;
}
/**
*
* 描述:描述:判斷字符串是否為空,如果為true則為空。與isEmpty不同,如果字符為" "也視為空字符
*
* @param str
* 字符串
* @return
*/
public static boolean isBlank(String str) {
boolean b = true;// 20140507 modify by liwei 修復(fù)對(duì)" "為false的bug
if (str == null) {
b = true;
} else {
int strLen = str.length();
if (strLen == 0) {
b = true;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
b = false;
break;
}
}
}
return b;
}
/**
*
* 描述:描述:判斷字符串是否為空,如果為true則不為空。與isNotEmpty不同,如果字符為" "也視為空字符
*
* @param str
* 字符串
* @return
*/
public static boolean isNotBlank(String str) {
int strLen = 0;
if (str != null)
strLen = str.length();
if (str == null || strLen == 0) {
return false;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}
/**
* 判斷字符串是否非空,如果為true則不為空
*
* @param string
* 字符串
* @return true/false
*/
public static boolean isNotEmpty(String string) {
return string != null && string.length() > 0;
}
/**
* 判斷字符串是否空,如果為true則為空
*
* @param str
* 字符串
* @return true/false
*/
public static boolean isEmpty(String str) {
if (str == null || str.trim().length() == 0) {
return true;
}
return false;
}
/**
* 向字符串添加上前綴,并以.作為分隔符
*
* @param name
* 需要添加前綴的字符串
* @param prefix
* 前綴
* @return 添加前綴后的字符串
*/
public static String qualify(String name, String prefix) {
if (name.startsWith("'")) {
return name;
}
return new StringBuffer(prefix.length() + name.length() + 1).append(prefix).append(DOT).append(name).toString();
}
/**
* 向字符串?dāng)?shù)組中的所有字符添加上前綴,前以點(diǎn)作為分隔符
*
* @param names
* 字符串?dāng)?shù)組
* @param prefix
* 前綴
* @return 添加前綴后的字符串?dāng)?shù)組
*/
public static String[] qualify(String[] names, String prefix) {
if (prefix == null) {
return names;
}
int len = names.length;
String[] qualified = new String[len];
for (int i = 0; i < len; i++) {
qualified[i] = qualify(prefix, names[i]);
}
return qualified;
}
/**
* 在字符串中,查找字符第一次出現(xiàn)的位置
*
* @param sqlString
* 原字符串
* @param string
* 需要查找到字符串
* @param startindex
* 開(kāi)始位置
* @return 第一個(gè)出現(xiàn)的位置
*/
public static int firstIndexOfChar(String sqlString, String string, int startindex) {
int matchAt = -1;
for (int i = 0; i < string.length(); i++) {
int curMatch = sqlString.indexOf(string.charAt(i), startindex);
if (curMatch >= 0) {
if (matchAt == -1) {
matchAt = curMatch;
} else {
matchAt = Math.min(matchAt, curMatch);
}
}
}
return matchAt;
}
/**
* 從字符串中提取指字長(zhǎng)度的字符。區(qū)分中英文。<br>
* 如果需要加省略號(hào),則將在指定長(zhǎng)度上少取3個(gè)字符寬度,末尾加上"......"。
*
* @param string
* 字符串
* @param length
* 要取的字符長(zhǎng)度,此為中文長(zhǎng)度,英文僅當(dāng)作半個(gè)字符。
* @param appendSuspensionPoints
* 是否需要加省略號(hào)
* @return 提取后的字符串
*/
public static String truncate(String string, int length, boolean appendSuspensionPoints) {
if (isEmpty(string) || length < 0) {
return string;
}
if (length == 0) {
return "";
}
int strLength = string.length(); // 字符串字符個(gè)數(shù)
int byteLength = byteLength(string); // 字符串字節(jié)長(zhǎng)度
length *= 2; // 換成字節(jié)長(zhǎng)度
// 判斷是否需要加省略號(hào)
boolean needSus = false;
if (appendSuspensionPoints && byteLength >= length) {
needSus = true;
// 如果需要加省略號(hào),則要少取2個(gè)字節(jié)用來(lái)加省略號(hào)
length -= 2;
}
StringBuffer result = new StringBuffer();
int count = 0;
for (int i = 0; i < strLength; i++) {
if (count >= length) { // 取完了
break;
}
char c = string.charAt(i);
if (isLetter(c)) { // Ascill字符
result.append(c);
count += 1;
} else { // 非Ascill字符
if (count == length - 1) { // 如果只要取1個(gè)字節(jié)了,而后面1個(gè)是漢字,就放空格
result.append(" ");
count += 1;
} else {
result.append(c);
count += 2;
}
}
}
if (needSus) {
result.append("...");
}
return result.toString();
}
/**
* 描述:判斷一個(gè)字符是Ascill字符還是其它字符(如漢,日,韓文字符)
*
* @param c
* 需要判斷的字符
* @return
*/
public static boolean isLetter(char c) {
int k = HEX_80;
return c / k == 0 ? true : false;
}
/**
* 得到一個(gè)字符串的長(zhǎng)度,顯示的長(zhǎng)度,一個(gè)漢字或日韓文長(zhǎng)度為2,英文字符長(zhǎng)度為1
*
* @param s
* ,需要得到長(zhǎng)度的字符串
* @return int, 得到的字符串長(zhǎng)度
*/
public static int byteLength(String s) {
char[] c = s.toCharArray();
int len = 0;
for (int i = 0; i < c.length; i++) {
if (isLetter(c[i])) {
len++;
} else {
len += 2;
}
}
return len;
}
/**
* 從字符串中提取指字長(zhǎng)度的字符
*
* @param string
* 字符串
* @param length
* 字符長(zhǎng)度
* @return 提取后的字符串
*/
public static String truncate(String string, int length) {
if (isEmpty(string)) {
return string;
}
if (string.length() <= length) {
return string;
} else {
return string.substring(0, length);
}
}
/**
* 去丟字符的左側(cè)空格
*
* @param value
* 字符串
* @return 去丟左側(cè)空格后的字符串
*/
public static String leftTrim(String value) {
String result = value;
if (result == null) {
return result;
}
char ch[] = result.toCharArray();
int index = -1;
for (int i = 0; i < ch.length; i++) {
if (!Character.isWhitespace(ch[i])) {
break;
}
index = i;
}
if (index != -1) {
result = result.substring(index + 1);
}
return result;
}
/**
* 去丟字符的右側(cè)空格
*
* @param value
* 字符串
* @return 去右側(cè)空格后的字符串
*/
public static String rightTrim(String value) {
String result = value;
if (result == null) {
return result;
}
char ch[] = result.toCharArray();
int endIndex = -1;
for (int i = ch.length - 1; i > -1; i--) {
if (!Character.isWhitespace(ch[i])) {
break;
}
endIndex = i;
}
if (endIndex != -1) {
result = result.substring(0, endIndex);
}
return result;
}
/**
* 把null字符串轉(zhuǎn)化為""
*
* @param source
* 空字符串
* @return 轉(zhuǎn)化后的字符串
*/
public static String n2s(String source) {
return source != null ? source : "";
}
/**
* 如果字符串為空,則返回默認(rèn)字符串
*
* @param source
* 源字符串
* @param defaultStr
* 默認(rèn)字符串
* @return 轉(zhuǎn)換后的字符串
*/
public static String n2s(String source, String defaultStr) {
return source != null ? source : defaultStr;
}
/**
* 將字符串格式化成 HTML 以SCRIPT變量 主要是替換單,雙引號(hào),以將內(nèi)容格式化輸出,適合于 HTML 中的顯示輸出
*
* @param str
* 要格式化的字符串
* @return 格式化后的字符串
*/
public static String toScript(String str) {
if (str == null) {
return null;
}
String html = new String(str);
html = replace(html, "\"", "\\\"");
html = replace(html, "\r\n", "\n");
html = replace(html, "\n", "\\n");
html = replace(html, "\t", " ");
html = replace(html, "\'", "\\\'");
html = replace(html, " ", " ");
html = replace(html, "</script>", "<\\/script>");
html = replace(html, "</SCRIPT>", "<\\/SCRIPT>");
return html;
}
/**
* 同于String#trim(),但是檢測(cè)null,如果原字符串為null,則仍然返回null
*
* @param s
* s
* @return
*/
public static String trim(String s) {
return s == null ? s : s.trim();
}
/**
* 對(duì)字符串進(jìn)行空格處理,如果字符串為null呀是空字符串, 則返回默認(rèn)的數(shù)字。
*
* @param source
* 需要進(jìn)行處理的字符串
* @param defaultValue
* 缺省值
* @return 字符串的數(shù)字值
*/
public static int strTrim(String source, int defaultValue) {
if (isEmpty(source)) {
return defaultValue;
}
try {
source = source.trim();
int value = (new Integer(source)).intValue();
return value;
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("數(shù)字轉(zhuǎn)換出錯(cuò),請(qǐng)檢查數(shù)據(jù)來(lái)源。返回默認(rèn)值");
return defaultValue;
}
}
/**
* 對(duì)字符串進(jìn)行過(guò)濾處理,如果字符串是null或?yàn)榭兆址?返回默認(rèn)值。
*
* @param source
* 需要進(jìn)行處理的字符串
* @param defaultValue
* 缺省值
* @return 過(guò)濾后的字符串
*/
public static String strTrim(String source, String defaultValue) {
if (StringHelper.isEmpty(source)) {
return defaultValue;
}
try {
source = source.trim();
return source;
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("字符串去空格失敗,返回默認(rèn)值");
return defaultValue;
}
}
/**
* 描述:為了防止跨站腳本攻擊,轉(zhuǎn)換<>這種尖括號(hào)。
*
* @param source
* @return
*/
public static String encodeURL(String source) {
if (source == null) {
return null;
}
String html = new String(source);
html = replace(html, "<", "<");
html = replace(html, ">", ">");
html = replace(html, "\"", """);
html = replace(html, " ", " ");
html = replace(html, "\'", "´");
html = replace(html, "\\", "\");
html = replace(html, "&", "&");
html = replace(html, "\r", "");
html = replace(html, "\n", "");
html = replace(html, "(", "(");
html = replace(html, ")", ")");
html = replace(html, "[", "[");
html = replace(html, "]", "]");
html = replace(html, ";", ";");
html = replace(html, "/", "/");
return html;
}
/**
* 把字符串中一些特定的字符轉(zhuǎn)換成html字符,如&、<、>、"號(hào)等
*
* @param source
* 需要進(jìn)行處理的字符串
* @return 處理后的字符串
*/
public static String encodeHtml(String source) {
if (source == null) {
return null;
}
String html = new String(source);
html = replace(html, "&", "&");
html = replace(html, "<", "<");
html = replace(html, ">", ">");
html = replace(html, "\"", """);
html = replace(html, " ", " ");
html = replace(html, "\'", "´");
return html;
}
/**
* 把一些html的字符串還原
*
* @param source
* 需要進(jìn)行處理的字符串
* @return 處理后的字符串
*/
public static String decodeHtml(String source) {
if (source == null) {
return null;
}
String html = new String(source);
html = replace(html, "&", "&");
html = replace(html, "<", "<");
html = replace(html, ">", ">");
html = replace(html, """, "\"");
html = replace(html, " ", " ");
html = replace(html, "\r\n", "\n");
html = replace(html, "\n", "<br>\n");
html = replace(html, "\t", " ");
html = replace(html, " ", " ");
return html;
}
/**
* 判斷字符串是否為布爾值,如true/false等
*
* @param source
* 需要進(jìn)行判斷的字符串
* @return 返回字符串的布爾值
*/
public static boolean isBoolean(String source) {
if (source.equalsIgnoreCase("true") || source.equalsIgnoreCase("false")) {
return true;
}
return false;
}
/**
* 去除字符串中的最后字符
*
* @param str
* 原字符串
* @param strMove
* 要去除字符 比如","
* @return 去除后的字符串
*/
public static String lastCharTrim(String str, String strMove) {
if (isEmpty(str)) {
return "";
}
String newStr = "";
if (str.lastIndexOf(strMove) != -1 && str.lastIndexOf(strMove) == str.length() - 1) {
newStr = str.substring(0, str.lastIndexOf(strMove));
}
return newStr;
}
/**
* 清除字符串里的html代碼
*
* @param html
* 需要進(jìn)行處理的字符串
* @return 清除html后的代碼
*/
public static String clearHtml(String html) {
if (isEmpty(html)) {
return "";
}
String patternStr = "(<[^>]*>)";
Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
Matcher matcher = null;
StringBuffer bf = new StringBuffer();
try {
matcher = pattern.matcher(html);
boolean first = true;
int start = 0;
int end = 0;
while (matcher.find()) {
start = matcher.start(1);
if (first) {
bf.append(html.substring(0, start));
first = false;
} else {
bf.append(html.substring(end, start));
}
end = matcher.end(1);
}
if (end < html.length()) {
bf.append(html.substring(end));
}
html = bf.toString();
return html;
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("清除html標(biāo)簽失敗");
} finally {
pattern = null;
matcher = null;
}
return html;
}
/**
* 把文杯格式轉(zhuǎn)換為html格式
*
* @param content
* 轉(zhuǎn)換的內(nèi)容
* @return
*/
public static String textFmtToHtmlFmt(String content) {
content = StringHelper.replace(content, " ", " ");
content = StringHelper.replace(content, "\r\n", "<br>");
content = StringHelper.replace(content, "\n", "<br>");
return content;
}
/**
*
* 描述:大寫(xiě)英文字母轉(zhuǎn)換成小寫(xiě)
*
* @param strIn
* 字符串參數(shù)
* @return
*/
public static String toLowerStr(String strIn) {
String strOut = new String(); // 輸出的字串
int len = strIn.length(); // 參數(shù)的長(zhǎng)度
int i = 0; // 計(jì)數(shù)器
char ch; // 存放參數(shù)的字符
while (i < len) {
ch = strIn.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
ch = (char) (ch - 'A' + 'a');
}
strOut += ch;
i++;
}
return strOut;
}
/**
*
* 描述:小寫(xiě)英文字母轉(zhuǎn)換成大寫(xiě)
*
* @param strIn
* 字符串參數(shù)
* @return
*/
public static String toUpperStr(String strIn) {
String strOut = new String(); // 輸出的字串
int len = strIn.length(); // 參數(shù)的長(zhǎng)度
int i = 0; // 計(jì)數(shù)器
char ch; // 存放參數(shù)的字符
while (i < len) {
ch = strIn.charAt(i);
if (ch >= 'a' && ch <= 'z') {
ch = (char) (ch - 'a' + 'A');
}
strOut += ch;
i++;
}
return strOut;
}
/**
* 貨幣縮寫(xiě),提供億和萬(wàn)兩個(gè)單位,并精確到小數(shù)點(diǎn)2位 切換到新的算法:對(duì)數(shù)算法
*
* @param original
* @return
*/
public static String currencyShortFor(String original) {
if (StringHelper.isBlank(original)) {
return "";
} else {
String shortFor = "";
double shortForValue = 0;
DecimalFormat df = new DecimalFormat("#.00");
try {
double account = Double.parseDouble(original);
if (account / 100000000 > 1) {
shortForValue = account / 100000000;
shortFor = df.format(shortForValue) + "億";
} else if (account / 10000 > 1) {
shortForValue = account / 10000;
shortFor = df.format(shortForValue) + "萬(wàn)";
} else {
shortFor = original;
}
} catch (NumberFormatException e) {
e.printStackTrace();
System.err.println("字符串[" + original + "]轉(zhuǎn)換成數(shù)字出錯(cuò)");
}
return shortFor;
}
}
/**
* 將日期格式由yyyyMMdd裝換為yyyy-MM-dd
*
* @param date
* Date string whose format is yyyyMMdd.
* @return
*/
public static String formatDate(String date) {
if (isBlank(date) || date.length() < 8) {
return "";
}
StringBuffer dateBuf = new StringBuffer();
dateBuf.append(date.substring(0, 4));
dateBuf.append("-");
dateBuf.append(date.substring(4, 6));
dateBuf.append("-");
dateBuf.append(date.substring(6, 8));
return dateBuf.toString();
}
/**
* 判斷是否為整數(shù)
*
* @param str
* 傳入的字符串
* @return 是整數(shù)返回true,否則返回false
*/
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^\\d+(\\.0)?$", Pattern.CASE_INSENSITIVE);
return pattern.matcher(str).matches();
}
/**
* 用于=中英文混排標(biāo)題中限定字符串長(zhǎng)度。保證顯示長(zhǎng)度最多只相差一個(gè)全角字符。
*
* @param string
* 需要截取的字符串
* @param byteCount
* 字節(jié)數(shù)(度量標(biāo)準(zhǔn)為中文為兩個(gè)字節(jié),ASCII字符為一個(gè)字節(jié),這樣子,剛好匹配ASCII為半角字符,而中文為全角字符,
* 保證在網(wǎng)頁(yè)上中英文混合的句子長(zhǎng)度一致)
* @return
* @throws UnsupportedEncodingException
*/
public static String substring(String string, int byteCount) throws UnsupportedEncodingException {
if (isBlank(string)) {
return string;
}
byte[] bytes = string.getBytes("Unicode");// 使用UCS-2編碼.
int viewBytes = 0; // 表示當(dāng)前的字節(jié)數(shù)(英文為單字節(jié),中文為雙字節(jié)的表示方法)
int ucs2Bytes = 2; // 要截取的字節(jié)數(shù),從第3個(gè)字節(jié)開(kāi)始,前兩位為位序。(UCS-2的表示方法)
// UCS-2每個(gè)字符使用兩個(gè)字節(jié)來(lái)編碼。
// ASCII n+=1,i+=2
// 中文 n+=2,i+=2
for (; ucs2Bytes < bytes.length && viewBytes < byteCount; ucs2Bytes++) {
// 奇數(shù)位置,如3、5、7等,為UCS2編碼中兩個(gè)字節(jié)的第二個(gè)字節(jié)
if (ucs2Bytes % 2 == 1) {
viewBytes++; // 低字節(jié),無(wú)論中英文,都算一個(gè)字節(jié)。
} else {
// 當(dāng)UCS2編碼的第一個(gè)字節(jié)不等于0時(shí),該UCS2字符為漢字,一個(gè)漢字算兩個(gè)字節(jié)
// 高位時(shí),僅中文的高位算一字節(jié)。
if (bytes[ucs2Bytes] != 0) {
viewBytes++;
}
}
}
// 截一半的漢字要保留
if (ucs2Bytes % 2 == 1) {
ucs2Bytes = ucs2Bytes + 1;
}
String result = new String(bytes, 0, ucs2Bytes, "Unicode");// 將字節(jié)流轉(zhuǎn)換為java默認(rèn)編碼UTF-8的字符串
if (bytes.length > ucs2Bytes) {
result += "...";
}
return result;
}
/**
* 描述:根據(jù)長(zhǎng)度截?cái)嘧执?
*
* @param str
* 字串
* @param length
* 截取長(zhǎng)度
* @return
*/
public static String[] splite(String str, int length) {
if (StringHelper.isEmpty(str)) {
return null;
}
String[] strArr = new String[(str.length() + length - 1) / length];
for (int i = 0; i < strArr.length; i++) {
if (str.length() > i * length + length - 1) {
strArr[i] = str.substring(i * length, i * length + length - 1);
} else {
strArr[i] = str.substring(i * length);
}
}
return strArr;
}
/**
* 描述:把某一個(gè)字符變成大寫(xiě)
*
* @param str
* str 字串
* @param index
* 第幾個(gè)字符
* @return
*/
public static String toUpOneChar(String str, int index) {
return toUpOrLowOneChar(str, index, 1);
}
/**
* 描述:把某一個(gè)字符變成小寫(xiě) 作者:李建 時(shí)間:Dec 17, 2010 9:42:32 PM
*
* @param str
* str 字串
* @param index
* 第幾個(gè)字符
* @return
*/
public static String toLowOneChar(String str, int index) {
return toUpOrLowOneChar(str, index, 0);
}
/**
* 描述:把某一個(gè)字符變成大寫(xiě)或小寫(xiě) 作者:李建 時(shí)間:Dec 17, 2010 9:39:32 PM
*
* @param str
* 字串
* @param index
* 第幾個(gè)字符
* @param upOrLow
* 大小寫(xiě) 1:大寫(xiě);0小寫(xiě)
* @return
*/
public static String toUpOrLowOneChar(String str, int index, int upOrLow) {
if (StringHelper.isNotEmpty(str) && index > -1 && index < str.length()) {
char[] chars = str.toCharArray();
if (upOrLow == 1) {
chars[index] = Character.toUpperCase(chars[index]);
} else {
chars[index] = Character.toLowerCase(chars[index]);
}
return new String(chars);
}
return str;
}
/**
* 將字符串用分隔符斷裂成字符串列表
*
* @param value
* 原字符串
* @param separator
* 分隔字符
* @return 結(jié)果列表
*/
public static List<String> split2List(String value, String separator) {
List<String> ls = new ArrayList<String>();
int i = 0, j = 0;
while ((i = value.indexOf(separator, i)) != -1) {
ls.add(value.substring(j, i));
++i;
j = i;
}
ls.add(value.substring(j));
return ls;
}
/**
* 將數(shù)組用分隔符連接成新字符串(split的逆方法)
*
* @param strs
* 字符串?dāng)?shù)組
* @param sep
* 分隔符
* @return 結(jié)果字符串
*/
public static String join(String[] strs, String sep) {
StringBuilder res = new StringBuilder();
for (int i = 0; i < strs.length; i++) {
res.append(strs[i] + sep);
}
return res.substring(0, res.length() - sep.length());
}
/**
* 獲得一個(gè)UUID
*
* @return String UUID
*/
public static String getUUID() {
String str = UUID.randomUUID().toString();// 標(biāo)準(zhǔn)的UUID格式為:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx(8-4-4-4-12)
// 去掉"-"符號(hào),不用replaceAll的原因與split一樣,replaceAll支持正則表達(dá)式,頻繁使用時(shí)效率不夠高(當(dāng)然偶爾用一下影響也不會(huì)特別嚴(yán)重)
return join(split(str, "-"), "");
}
/**
* <pre>
* 例: String strVal="This is a dog"; String
* strResult=CTools.replace(strVal,"dog","cat"); 結(jié)果: strResult equals
* "This is cat"
*
* @param strSrc
* 要進(jìn)行替換操作的字符串
* @param strOld
* 要查找的字符串
* @param strNew
* 要替換的字符串
* @return 替換后的字符串
*
* <pre>
*/
public static final String replaceAllStr(String strSrc, String strOld, String strNew) {
if (strSrc == null || strOld == null || strNew == null)
return "";
int i = 0;
if (strOld.equals(strNew)) // 避免新舊字符一樣產(chǎn)生死循環(huán)
return strSrc;
if ((i = strSrc.indexOf(strOld, i)) >= 0) {
char[] arr_cSrc = strSrc.toCharArray();
char[] arr_cNew = strNew.toCharArray();
int intOldLen = strOld.length();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
buf.append(arr_cSrc, 0, i).append(arr_cNew);
i += intOldLen;
int j = i;
while ((i = strSrc.indexOf(strOld, i)) > 0) {
buf.append(arr_cSrc, j, i - j).append(arr_cNew);
i += intOldLen;
j = i;
}
buf.append(arr_cSrc, j, arr_cSrc.length - j);
return buf.toString();
}
return strSrc;
}
/**
* 用于將字符串中的特殊字符轉(zhuǎn)換成Web頁(yè)中可以安全顯示的字符串 可對(duì)表單數(shù)據(jù)據(jù)進(jìn)行處理對(duì)一些頁(yè)面特殊字符進(jìn)行處理如'
* <','>','"',''','&'
*
* @param strSrc
* 要進(jìn)行替換操作的字符串
* @return 替換特殊字符后的字符串
* @since 1.0
*/
public static String htmlEncode(String strSrc) {
if (strSrc == null)
return "";
char[] arr_cSrc = strSrc.toCharArray();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
char ch;
for (int i = 0; i < arr_cSrc.length; i++) {
ch = arr_cSrc[i];
if (ch == '<')
buf.append("<");
else if (ch == '>')
buf.append(">");
else if (ch == '"')
buf.append(""");
else if (ch == '\'')
buf.append("'");
else if (ch == '&')
buf.append("&");
else
buf.append(ch);
}
return buf.toString();
}
/**
* 用于將字符串中的特殊字符轉(zhuǎn)換成Web頁(yè)中可以安全顯示的字符串 可對(duì)表單數(shù)據(jù)據(jù)進(jìn)行處理對(duì)一些頁(yè)面特殊字符進(jìn)行處理如'
* <','>','"',''','&'
*
* @param strSrc
* 要進(jìn)行替換操作的字符串
* @param quotes
* 為0時(shí)單引號(hào)和雙引號(hào)都替換,為1時(shí)不替換單引號(hào),為2時(shí)不替換雙引號(hào),為3時(shí)單引號(hào)和雙引號(hào)都不替換
* @return 替換特殊字符后的字符串
* @since 1.0
*/
public static String htmlEncode(String strSrc, int quotes) {
if (strSrc == null)
return "";
if (quotes == 0) {
return htmlEncode(strSrc);
}
char[] arr_cSrc = strSrc.toCharArray();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
char ch;
for (int i = 0; i < arr_cSrc.length; i++) {
ch = arr_cSrc[i];
if (ch == '<')
buf.append("<");
else if (ch == '>')
buf.append(">");
else if (ch == '"' && quotes == 1)
buf.append(""");
else if (ch == '\'' && quotes == 2)
buf.append("'");
else if (ch == '&')
buf.append("&");
else
buf.append(ch);
}
return buf.toString();
}
/**
* 和htmlEncode正好相反
*
* @param strSrc
* 要進(jìn)行轉(zhuǎn)換的字符串
* @return 轉(zhuǎn)換后的字符串
* @since 1.0
*/
public static String htmlDecode(String strSrc) {
if (strSrc == null)
return "";
strSrc = strSrc.replaceAll("<", "<");
strSrc = strSrc.replaceAll(">", ">");
strSrc = strSrc.replaceAll(""", "\"");
strSrc = strSrc.replaceAll("'", "'");
strSrc = strSrc.replaceAll("&", "&");
return strSrc;
}
/**
* 實(shí)際處理 return toChineseNoReplace(null2Blank(str));
*
* @param str
* 要進(jìn)行處理的字符串
* @return 轉(zhuǎn)換后的字符串
* @see fs_com.utils.CTools#toChinese
* @see fs_com.utils.CTools#null2Blank
*/
public static String toChineseAndHtmlEncode(String str, int quotes) {
try {
if (str == null) {
return "";
} else {
str = str.trim();
str = new String(str.getBytes("ISO8859_1"), "GBK");
String htmlEncode = htmlEncode(str, quotes);
return htmlEncode;
}
} catch (Exception exp) {
return "";
}
}
/**
* 把null值和""值轉(zhuǎn)換成 主要應(yīng)用于頁(yè)面表格格的顯示
*
* @param str
* 要進(jìn)行處理的字符串
* @return 轉(zhuǎn)換后的字符串
*/
public static String str4Table(String str) {
if (str == null)
return " ";
else if (str.equals(""))
return " ";
else
return str;
}
}
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
- Java8優(yōu)雅的字符串拼接工具類StringJoiner實(shí)例代碼
- java字符串格式化(String類format方法)
- java將String字符串轉(zhuǎn)換為L(zhǎng)ist<Long>類型實(shí)例方法
- Java String類簡(jiǎn)單用法實(shí)戰(zhàn)示例【字符串輸出、比較】
- 詳解Java中字符串緩沖區(qū)StringBuffer類的使用
- 辨析Java中的String與StringBuffer及StringBuilder字符串類
- Java中char數(shù)組(字符數(shù)組)與字符串String類型的轉(zhuǎn)換方法
- 關(guān)于Java中String類字符串的解析
- Java String類的性質(zhì)與比較
相關(guān)文章
java Beanutils.copyProperties( )用法詳解
這篇文章主要介紹了java Beanutils.copyProperties( )用法詳解,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
java IO流將一個(gè)文件拆分為多個(gè)子文件代碼示例
這篇文章主要介紹了java IO流將一個(gè)文件拆分為多個(gè)子文件代碼示例,具有一定借鑒價(jià)值,需要的朋友可以參考下。2017-12-12
關(guān)于PreparedStatement的setObject作用及說(shuō)明
這篇文章主要介紹了關(guān)于PreparedStatement的setObject作用及說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03
springboot攔截器不攔截靜態(tài)資源,只攔截controller的實(shí)現(xiàn)方法
這篇文章主要介紹了springboot攔截器不攔截靜態(tài)資源,只攔截controller的實(shí)現(xiàn)方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-07-07
SpringBoot對(duì)Controller進(jìn)行單元測(cè)試的實(shí)現(xiàn)代碼 附亂碼解決方案
這篇文章主要介紹了SpringBoot對(duì)Controller進(jìn)行單元測(cè)試的實(shí)現(xiàn)代碼 附亂碼解決方案,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-04-04
Spring通過(guò)三級(jí)緩存解決循環(huán)依賴問(wèn)題的過(guò)程詳解
循環(huán)依賴指的是在對(duì)象之間存在相互依賴關(guān)系,形成一個(gè)閉環(huán),導(dǎo)致無(wú)法準(zhǔn)確地完成對(duì)象的創(chuàng)建和初始化,本文主要介紹了Spring通過(guò)三級(jí)緩存解決循環(huán)依賴的方法,需要的可以參考下2023-10-10
Java實(shí)現(xiàn)List轉(zhuǎn)換為Map的方法小結(jié)
這篇文章主要為大家詳細(xì)介紹了Java實(shí)現(xiàn)List轉(zhuǎn)換為Map的一些常見(jiàn)的方法,文中的示例代碼講解詳細(xì),具有一定的借鑒價(jià)值,有需要的小伙伴可以參考一下2024-03-03

