本文实例为大家分享了java常用工具类的具体代码,供大家参考,具体内容如下
Reflect反射工具类
package com.jarvis.base.util;
public class ReflectHelper {
public static Class> classForName(String name) throws ClassNotFoundException {
try {
return Thread.currentThread().getContextClassLoader().loadClass(name);
}
catch (ClassNotFoundException e) {
e.printStackTrace();
System.err.println("类[" + name + "]加载出错");
} catch (SecurityException e) {
e.printStackTrace();
System.err.println("类[" + name + "]加载出错");
}
return Class.forName(name);
}
public static Object objectForName(String name) {
try {
return Class.forName(name).newInstance();
} catch (Exception ex) {
ex.printStackTrace();
System.err.println("类[" + name + "]获取对象实例出错");
}
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;
public final class StringHelper {
private StringHelper() {
}
public static final String EMPTY_STRING = "";
public static final char DOT = '.';
public static final char UNDERSCORE = '_';
public static final String COMMA_SPACE = ", ";
public static final String COMMA = ",";
public static final String OPEN_PAREN = "(";
public static final String CLOSE_PAREN = ")";
public static final char SINGLE_QUOTE = ''';
public static final String CRLF = "rn";
public static final int FIANL_TWELVE = 12;
public static final int HEX_80 = 0x80;
public static final int HEX_FF = 0xff;
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();
}
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();
}
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;
}
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();
}
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;
// 通过截取字符串的方式,替换字符串
while ((pos = source.indexOf(old, posStart)) >= 0) {
output.append(source.substring(posStart, pos));
output.append(replace);
posStart = pos + oldLen;
}
// 如果还有没有处理的字符串,则都添加到新字符串后面
if (posStart < sourceLen) {
output.append(source.substring(posStart));
}
return output.toString();
}
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();
}
}
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();
}
}
public static String[] split(String list, String seperators) {
return split(list, seperators, false);
}
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;
}
public static String unqualify(String qualifiedName) {
return unqualify(qualifiedName, ".");
}
public static String unqualify(String qualifiedName, String seperator) {
return qualifiedName.substring(qualifiedName.lastIndexOf(seperator) + 1);
}
public static String qualifier(String qualifiedName) {
int loc = qualifiedName.lastIndexOf(".");
if (loc < 0) {
return EMPTY_STRING;
} else {
return qualifiedName.substring(0, loc);
}
}
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;
}
public static String suffix(String name, String suffix) {
return (suffix == null) ? name : name + suffix;
}
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;
}
public static String prefix(String name, String prefix) {
return (prefix == null) ? name : prefix + name;
}
public static boolean booleanValue(String tfString) {
String trimmed = tfString.trim().toLowerCase();
return trimmed.equals("true") || trimmed.equals("t");
}
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();
}
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;
}
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;
}
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;
}
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;
}
public static boolean isBlank(String str) {
boolean b = true;// 20140507 modify by liwei 修复对" "为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;
}
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;
}
public static boolean isNotEmpty(String string) {
return string != null && string.length() > 0;
}
public static boolean isEmpty(String str) {
if (str == null || str.trim().length() == 0) {
return true;
}
return false;
}
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();
}
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;
}
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;
}
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(); // 字符串字符个数
int byteLength = byteLength(string); // 字符串字节长度
length *= 2; // 换成字节长度
// 判断是否需要加省略号
boolean needSus = false;
if (appendSuspensionPoints && byteLength >= length) {
needSus = true;
// 如果需要加省略号,则要少取2个字节用来加省略号
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个字节了,而后面1个是汉字,就放空格
result.append(" ");
count += 1;
} else {
result.append(c);
count += 2;
}
}
}
if (needSus) {
result.append("...");
}
return result.toString();
}
public static boolean isLetter(char c) {
int k = HEX_80;
return c / k == 0 ? true : false;
}
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;
}
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);
}
}
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;
}
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;
}
public static String n2s(String source) {
return source != null ? source : "";
}
public static String n2s(String source, String defaultStr) {
return source != null ? source : defaultStr;
}
public static String toscript(String str) {
if (str == null) {
return null;
}
String html = new String(str);
html = replace(html, """, "\"");
html = replace(html, "rn", "n");
html = replace(html, "n", "\n");
html = replace(html, "t", " ");
html = replace(html, "'", "\'");
html = replace(html, " ", " ");
html = replace(html, "", "<\/script>");
html = replace(html, "", "<\/script>");
return html;
}
public static String trim(String s) {
return s == null ? s : s.trim();
}
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("数字转换出错,请检查数据来源。返回默认值");
return defaultValue;
}
}
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("字符串去空格失败,返回默认值");
return defaultValue;
}
}
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;
}
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;
}
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, "rn", "n");
html = replace(html, "n", "
n");
html = replace(html, "t", " ");
html = replace(html, " ", " ");
return html;
}
public static boolean isBoolean(String source) {
if (source.equalsIgnoreCase("true") || source.equalsIgnoreCase("false")) {
return true;
}
return false;
}
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;
}
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标签失败");
} finally {
pattern = null;
matcher = null;
}
return html;
}
public static String textFmtToHtmlFmt(String content) {
content = StringHelper.replace(content, " ", " ");
content = StringHelper.replace(content, "rn", "
");
content = StringHelper.replace(content, "n", "
");
return content;
}
public static String toLowerStr(String strIn) {
String strOut = new String(); // 输出的字串
int len = strIn.length(); // 参数的长度
int i = 0; // 计数器
char ch; // 存放参数的字符
while (i < len) {
ch = strIn.charAt(i);
if (ch >= 'A' && ch <= 'Z') {
ch = (char) (ch - 'A' + 'a');
}
strOut += ch;
i++;
}
return strOut;
}
public static String toUpperStr(String strIn) {
String strOut = new String(); // 输出的字串
int len = strIn.length(); // 参数的长度
int i = 0; // 计数器
char ch; // 存放参数的字符
while (i < len) {
ch = strIn.charAt(i);
if (ch >= 'a' && ch <= 'z') {
ch = (char) (ch - 'a' + 'A');
}
strOut += ch;
i++;
}
return strOut;
}
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) + "万";
} else {
shortFor = original;
}
} catch (NumberFormatException e) {
e.printStackTrace();
System.err.println("字符串[" + original + "]转换成数字出错");
}
return shortFor;
}
}
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();
}
public static boolean isInteger(String str) {
Pattern pattern = Pattern.compile("^\d+(\.0)?$", Pattern.CASE_INSENSITIVE);
return pattern.matcher(str).matches();
}
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; // 表示当前的字节数(英文为单字节,中文为双字节的表示方法)
int ucs2Bytes = 2; // 要截取的字节数,从第3个字节开始,前两位为位序。(UCS-2的表示方法)
// UCS-2每个字符使用两个字节来编码。
// ASCII n+=1,i+=2
// 中文 n+=2,i+=2
for (; ucs2Bytes < bytes.length && viewBytes < byteCount; ucs2Bytes++) {
// 奇数位置,如3、5、7等,为UCS2编码中两个字节的第二个字节
if (ucs2Bytes % 2 == 1) {
viewBytes++; // 低字节,无论中英文,都算一个字节。
} else {
// 当UCS2编码的第一个字节不等于0时,该UCS2字符为汉字,一个汉字算两个字节
// 高位时,仅中文的高位算一字节。
if (bytes[ucs2Bytes] != 0) {
viewBytes++;
}
}
}
// 截一半的汉字要保留
if (ucs2Bytes % 2 == 1) {
ucs2Bytes = ucs2Bytes + 1;
}
String result = new String(bytes, 0, ucs2Bytes, "Unicode");// 将字节流转换为java默认编码UTF-8的字符串
if (bytes.length > ucs2Bytes) {
result += "...";
}
return result;
}
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;
}
public static String toUpOneChar(String str, int index) {
return toUpOrLowOneChar(str, index, 1);
}
public static String toLowOneChar(String str, int index) {
return toUpOrLowOneChar(str, index, 0);
}
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;
}
public static List split2List(String value, String separator) {
List ls = new ArrayList();
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;
}
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());
}
public static String getUUID() {
String str = UUID.randomUUID().toString();// 标准的UUID格式为:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxx(8-4-4-4-12)
// 去掉"-"符号,不用replaceAll的原因与split一样,replaceAll支持正则表达式,频繁使用时效率不够高(当然偶尔用一下影响也不会特别严重)
return join(split(str, "-"), "");
}
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)) // 避免新旧字符一样产生死循环
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;
}
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();
}
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();
}
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;
}
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 "";
}
}
public static String str4Table(String str) {
if (str == null)
return " ";
else if (str.equals(""))
return " ";
else
return str;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。



