当前位置: 移动技术网 > IT编程>开发语言>Java > java常用工具类 Reflect反射工具类、String字符串工具类

java常用工具类 Reflect反射工具类、String字符串工具类

2019年07月19日  | 移动技术网IT编程  | 我要评论

本文实例为大家分享了java常用工具类的具体代码,供大家参考,具体内容如下

reflect反射工具类

package com.jarvis.base.util;

/**
 * 
 * 
 * @title: reflecthelper.java
 * @package com.jarvis.base.util
 * @description: 反射工具类
 * @version v1.0 
 */
public class reflecthelper {

 /**
 * 提指定的类载入以系统中
 *
 * @param name
 *   类名称
 * @return 类对象
 * @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 + "]加载出错");
 } catch (securityexception e) {
 e.printstacktrace();
 system.err.println("类[" + name + "]加载出错");
 }
 return class.forname(name);
 }

 /**
 * 根据名称生成指定的对象
 *
 * @param name
 *   类名称
 * @return 具体的对象,若发生异常,则返回null
 */
 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;

/**
 * 
 * 
 * @title: stringhelper.java
 * @package com.jarvis.base.utils
 * @description:
 * @version v1.0 字符串处理工具类。
 */
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 = "\r\n";

 /**
 * 常量 12
 */
 public static final int fianl_twelve = 12;

 /**
 * 十六进制常量 0x80
 */
 public static final int hex_80 = 0x80;

 /**
 * 十六进制常量 0xff
 */
 public static final int hex_ff = 0xff;

 /**
 * 把字符数组,转化为一个字符
 *
 * @param seperator
 *   字符分隔符
 * @param strings
 *   数组对象
 * @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();
 }

 /**
 * 把迭代对象转化为一个字符串
 *
 * @param seperator
 *   分隔符
 * @param objects
 *   迭代器对象
 * @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();
 }

 /**
 * 把两个字符串数组的元素用分隔符连接,生成新的数组,生成的数组以第一个字符串数组为参照,与其长度相同。
 *
 * @param x
 *   字符串数组
 * @param seperator
 *   分隔符
 * @param y
 *   字符串数组
 * @return 组合后的字符串数组
 */
 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;
 }

 /**
 * 生成一个重复的字符串,如需要重复*10次,则生成:**********。
 *
 * @param string
 *   重复元素
 * @param times
 *   重复次数
 * @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();
 }

 /**
 * 字符串替换处理,把旧的字符串替换为新的字符串,主要是通过字符串查找进行处理
 *
 * @param source
 *   需要进行替换的字符串
 * @param old
 *   需要进行替换的字符串
 * @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;

 // 通过截取字符串的方式,替换字符串
 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();
 }

 /**
 * 替换字符,如果指定进行全替换,必须设wholewords=true,否则只替换最后出现的字符。
 *
 * @param template
 *   字符模板
 * @param placeholder
 *   需要替换的字符
 * @param replacement
 *   新的字符
 * @param wholewords
 *   是否需要全替换,true为需要,false为不需要。如果不需要,则只替换最后出现的字符。
 * @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();
 }
 }

 /**
 * 替换字符,只替换第一次出现的字符串。
 *
 * @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();
 }
 }

 /**
 * 把字符串,按指字的分隔符分隔为字符串数组
 *
 * @param seperators
 *   分隔符
 * @param list
 *   字符串
 * @return 字符串数组
 */
 public static string[] split(string list, string seperators) {
 return split(list, seperators, false);
 }

 /**
 * 把字符串,按指字的分隔符分隔为字符串数组
 *
 * @param seperators
 *   分隔符
 * @param list
 *   字符串
 * @param include
 *   是否需要把分隔符也返回
 * @return 字符串数组
 */
 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);
 }
 }

 /**
 * 向字符串数组中的所有元素添加上后缀
 *
 * @param columns
 *   字符串数组
 * @param suffix
 *   后缀
 * @return 添加后缀后的数组
 */
 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;
 }

 /**
 * 向字符串数组中的所有元素,添加上前缀
 *
 * @param columns
 *   需要添加前缀的字符串数组
 * @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
 *   需要进行判断真/假的字符串
 * @return true/false
 */
 public static boolean booleanvalue(string tfstring) {
 string trimmed = tfstring.trim().tolowercase();
 return trimmed.equals("true") || trimmed.equals("t");
 }

 /**
 * 把对象数组转化为字符串
 *
 * @param array
 *   对象数组
 * @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();
 }

 /**
 * 描述:把数组中的所有元素出现的字符串进行替换,把旧字符串替换为新字符数组的所有元素,只替换第一次出现的字符。
 * 
 * @param string
 *   需要替换的数组
 * @param placeholders
 *   需要替换的字符串
 * @param replacements
 *   新字符串数组
 * @return 替换后的字符串数组
 */
 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;
 }

 /**
 * 把数组中的所有元素出现的字符串进行替换,把旧字符串替换为新字符数组的所有元素,只替换第一次出现的字符。
 *
 * @param strings
 *   需要替换的数组
 * @param placeholder
 *   需要替换的字符串
 * @param replacements
 *   新字符串数组
 * @return 替换后的字符串数组
 */
 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;
 }

 /**
 * 统计char在字符串中出现在次数,如"s"在字符串"string"中出现的次数
 *
 * @param string
 *   字符串
 * @param character
 *   需要进行统计的char
 * @return 数量
 */
 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;
 }

 /**
 * 描述:计算字符串中未引用的字符
 * 
 * @param string
 *   字符串
 * @param character
 *   字符
 * @return 未引用的字符数
 */
 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 修复对" "为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();
 }

 /**
 * 向字符串数组中的所有字符添加上前缀,前以点作为分隔符
 *
 * @param names
 *   字符串数组
 * @param prefix
 *   前缀
 * @return 添加前缀后的字符串数组
 */
 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;
 }

 /**
 * 在字符串中,查找字符第一次出现的位置
 *
 * @param sqlstring
 *   原字符串
 * @param string
 *   需要查找到字符串
 * @param startindex
 *   开始位置
 * @return 第一个出现的位置
 */
 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;
 }

 /**
 * 从字符串中提取指字长度的字符。区分中英文。<br>
 * 如果需要加省略号,则将在指定长度上少取3个字符宽度,末尾加上"......"。
 *
 * @param string
 *   字符串
 * @param length
 *   要取的字符长度,此为中文长度,英文仅当作半个字符。
 * @param appendsuspensionpoints
 *   是否需要加省略号
 * @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(); // 字符串字符个数
 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();
 }

 /**
 * 描述:判断一个字符是ascill字符还是其它字符(如汉,日,韩文字符)
 * 
 * @param c
 *   需要判断的字符
 * @return
 */
 public static boolean isletter(char c) {
 int k = hex_80;
 return c / k == 0 ? true : false;
 }

 /**
 * 得到一个字符串的长度,显示的长度,一个汉字或日韩文长度为2,英文字符长度为1
 *
 * @param s
 *   ,需要得到长度的字符串
 * @return int, 得到的字符串长度
 */
 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;
 }

 /**
 * 从字符串中提取指字长度的字符
 *
 * @param string
 *   字符串
 * @param length
 *   字符长度
 * @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);
 }
 }

 /**
 * 去丢字符的左侧空格
 *
 * @param value
 *   字符串
 * @return 去丢左侧空格后的字符串
 */
 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;
 }

 /**
 * 去丢字符的右侧空格
 *
 * @param value
 *   字符串
 * @return 去右侧空格后的字符串
 */
 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字符串转化为""
 *
 * @param source
 *   空字符串
 * @return 转化后的字符串
 */
 public static string n2s(string source) {
 return source != null ? source : "";
 }

 /**
 * 如果字符串为空,则返回默认字符串
 *
 * @param source
 *   源字符串
 * @param defaultstr
 *   默认字符串
 * @return 转换后的字符串
 */
 public static string n2s(string source, string defaultstr) {
 return source != null ? source : defaultstr;
 }

 /**
 * 将字符串格式化成 html 以script变量 主要是替换单,双引号,以将内容格式化输出,适合于 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(),但是检测null,如果原字符串为null,则仍然返回null
 *
 * @param s
 *   s
 * @return
 */
 public static string trim(string s) {
 return s == null ? s : s.trim();
 }

 /**
 * 对字符串进行空格处理,如果字符串为null呀是空字符串, 则返回默认的数字。
 *
 * @param source
 *   需要进行处理的字符串
 * @param defaultvalue
 *   缺省值
 * @return 字符串的数字值
 */
 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;
 }
 }

 /**
 * 对字符串进行过滤处理,如果字符串是null或为空字符串, 返回默认值。
 *
 * @param source
 *   需要进行处理的字符串
 * @param defaultvalue
 *   缺省值
 * @return 过滤后的字符串
 */
 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;
 }
 }

 /**
 * 描述:为了防止跨站脚本攻击,转换<>这种尖括号。
 * 
 * @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;
 }

 /**
 * 把字符串中一些特定的字符转换成html字符,如&、<、>、"号等
 *
 * @param source
 *   需要进行处理的字符串
 * @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
 *   需要进行处理的字符串
 * @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
 *   需要进行判断的字符串
 * @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
 *   需要进行处理的字符串
 * @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标签失败");
 } finally {
 pattern = null;
 matcher = null;
 }
 return html;
 }

 /**
 * 把文杯格式转换为html格式
 *
 * @param content
 *   转换的内容
 * @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;
 }

 /**
 * 
 * 描述:大写英文字母转换成小写
 * 
 * @param strin
 *   字符串参数
 * @return
 */
 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;
 }

 /**
 * 
 * 描述:小写英文字母转换成大写
 * 
 * @param strin
 *   字符串参数
 * @return
 */
 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;
 }

 /**
 * 货币缩写,提供亿和万两个单位,并精确到小数点2位 切换到新的算法:对数算法
 * 
 * @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) + "万";
 } else {
  shortfor = original;
 }
 } catch (numberformatexception e) {
 e.printstacktrace();
 system.err.println("字符串[" + original + "]转换成数字出错");
 }

 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();
 }

 /**
 * 判断是否为整数
 * 
 * @param str
 *   传入的字符串
 * @return 是整数返回true,否则返回false
 */
 public static boolean isinteger(string str) {
 pattern pattern = pattern.compile("^\\d+(\\.0)?$", pattern.case_insensitive);
 return pattern.matcher(str).matches();

 }

 /**
 * 用于=中英文混排标题中限定字符串长度。保证显示长度最多只相差一个全角字符。
 * 
 * @param string
 *   需要截取的字符串
 * @param bytecount
 *   字节数(度量标准为中文为两个字节,ascii字符为一个字节,这样子,刚好匹配ascii为半角字符,而中文为全角字符,
 *   保证在网页上中英文混合的句子长度一致)
 * @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; // 表示当前的字节数(英文为单字节,中文为双字节的表示方法)
 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;
 }

 /**
 * 描述:根据长度截断字串
 * 
 * @param str
 *   字串
 * @param length
 *   截取长度
 * @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;
 }

 /**
 * 描述:把某一个字符变成大写
 * 
 * @param str
 *   str 字串
 * @param index
 *   第几个字符
 * @return
 */
 public static string touponechar(string str, int index) {
 return touporlowonechar(str, index, 1);
 }

 /**
 * 描述:把某一个字符变成小写 作者:李建 时间:dec 17, 2010 9:42:32 pm
 * 
 * @param str
 *   str 字串
 * @param index
 *   第几个字符
 * @return
 */
 public static string tolowonechar(string str, int index) {
 return touporlowonechar(str, index, 0);
 }

 /**
 * 描述:把某一个字符变成大写或小写 作者:李建 时间:dec 17, 2010 9:39:32 pm
 * 
 * @param str
 *   字串
 * @param index
 *   第几个字符
 * @param uporlow
 *   大小写 1:大写;0小写
 * @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 结果列表
 */
 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;
 }

 /**
 * 将数组用分隔符连接成新字符串(split的逆方法)
 * 
 * @param strs
 *   字符串数组
 * @param sep
 *   分隔符
 * @return 结果字符串
 */
 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());
 }

 /**
 * 获得一个uuid
 * 
 * @return string uuid
 */
 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, "-"), "");
 }

 /**
 * <pre>
 * 例: string strval="this is a dog"; string
 * strresult=ctools.replace(strval,"dog","cat"); 结果: strresult equals
 * "this is cat"
 *
 * @param strsrc
 *   要进行替换操作的字符串
 * @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)) // 避免新旧字符一样产生死循环
 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;
 }

 /**
 * 用于将字符串中的特殊字符转换成web页中可以安全显示的字符串 可对表单数据据进行处理对一些页面特殊字符进行处理如'
 * <','>','"',''','&'
 * 
 * @param strsrc
 *   要进行替换操作的字符串
 * @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();
 }

 /**
 * 用于将字符串中的特殊字符转换成web页中可以安全显示的字符串 可对表单数据据进行处理对一些页面特殊字符进行处理如'
 * <','>','"',''','&'
 * 
 * @param strsrc
 *   要进行替换操作的字符串
 * @param quotes
 *   为0时单引号和双引号都替换,为1时不替换单引号,为2时不替换双引号,为3时单引号和双引号都不替换
 * @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
 *   要进行转换的字符串
 * @return 转换后的字符串
 * @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;
 }

 /**
 * 实际处理 return tochinesenoreplace(null2blank(str));
 * 
 * @param str
 *   要进行处理的字符串
 * @return 转换后的字符串
 * @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值和""值转换成  主要应用于页面表格格的显示
 * 
 * @param str
 *   要进行处理的字符串
 * @return 转换后的字符串
 */
 public static string str4table(string str) {
 if (str == null)
 return " ";
 else if (str.equals(""))
 return " ";
 else
 return str;
 }

}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持移动技术网。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网