`
myCsdn_taoge
  • 浏览: 38604 次
  • 性别: Icon_minigender_1
  • 来自: 沈阳
文章分类
社区版块
存档分类
最新评论
阅读更多
package com.tools;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import com.opensymphony.xwork2.inject.ContainerBuilder.Command;

public class BaseUtil {

	public static final String PROJECT_DEFAULT_ENCODING = "UTF-8";

		
	
/**

* 判断字符串是否为空
*/
public static boolean isEmpty(Object arg) {
if (StringSafe(arg).equals("")) {
return true;
}
return false;
}

/**
* 转换null字符串为""
*/
public static String StringSafe(Object strParam) {
String value = "";
if (strParam == null) {
value = "";
} else {
try {
value = String.valueOf(strParam);
} catch (Exception e) {
value = "";
}
}
if (value.equals("null") || value.equals("[]")) {
value = "";
}
return value.trim();
}

/**
* 将ISO流内容转换为项目默认编码格式内容
*/
public static String ISO2DefaultCode(String arg) {
String strWrk = "";
arg = StringSafe(arg);
try {
strWrk = new String(arg.getBytes("ISO-8859-1"), "UTF-8");
} catch (Exception e) {
strWrk = "*** ERROR convStr()";
}
return strWrk;
}

/**
* 将字符串内容转换为项目UTF-8编码格式内容
*/
public static String ISO2UTF_8Code(String arg) {

// String utf8 = new String(t.getBytes( "UTF-8")); 
// System.out.println(utf8); 
// String unicode = new String(utf8.getBytes(),"UTF-8"); 
// System.out.println(unicode); 
// String gbk = new String(unicode.getBytes("GBK"));   
// System.out.println(gbk); 



String strWrk = "";
arg = StringSafe(arg);
try {
strWrk = new String(arg.getBytes("UTF-8"), "UTF-8");
} catch (Exception e) {
strWrk = "*** ERROR convStr()";
}
return strWrk;
}

/*
* 将GBK编码格式转换为UTF-8
*/
public static String getUTF8StringFromGBKString(String gbkStr){  
   try {  
       return new String(getUTF8BytesFromGBKString(gbkStr), "UTF-8");  
       } catch (UnsupportedEncodingException e) {  
        throw new InternalError();  
   }  
   }

/**
*
* @param gbkStr
* @return
* @description 将UTF-8编码格式转换成GBK格式
* @version 1.0
* @author liutao
* @update Apr 15, 2013 10:20:05 AM
*/
public static byte[] getUTF8BytesFromGBKString(String gbkStr) {  
   int n = gbkStr.length();  
   byte[] utfBytes = new byte[3 * n];  
    int k = 0;  
    for (int i = 0; i < n; i++) {  
        int m = gbkStr.charAt(i);  
        if (m < 128 && m >= 0) {  
            utfBytes[k++] = (byte) m;  
            continue;  
        }  
        utfBytes[k++] = (byte) (0xe0 | (m >> 12));  
        utfBytes[k++] = (byte) (0x80 | ((m >> 6) & 0x3f));  
        utfBytes[k++] = (byte) (0x80 | (m & 0x3f));  
    }  
    if (k < utfBytes.length) {  
        byte[] tmp = new byte[k];  
        System.arraycopy(utfBytes, 0, tmp, 0, k);  
       return tmp;  
    }  
    return utfBytes;  




/**
* 将项目默认编码格式内容转换为ISO流内容
*/
// public static String DefaultCode2ISO(String arg) {
// String strWrk = "";
// arg = StringSafe(arg);
// try {
// strWrk = new String(arg.getBytes(Command.ENCODING), "ISO-8859-1");
// } catch (Exception e) {
// strWrk = "*** ERROR convStr()";
// }
// return strWrk;
// }

/***************************************************************************
* 字符串左补位<br>
* orginString 需要补位的字符串<br>
* addStr 需要填补的内容 len 需要填补的长度
*/
public static String padLeft(String orginString, String addStr, int len) {
StringBuffer strBuffer = new StringBuffer("");
if (orginString == null) {
orginString = "";
}
if (orginString.length() >= len) {
return orginString;
}
if (addStr != null) {
//System.out.println(strBuffer.length()+"*");
while (strBuffer.length() + orginString.length() < len) {
System.out.println(strBuffer.length()+orginString.length());
strBuffer.append(addStr);
}
}
strBuffer.append(orginString);
return strBuffer.toString();
}

/***************************************************************************
* 字符串右补位<br>
* orginString 需要补位的字符串<br>
* addStr 需要填补的内容 len 需要填补的长度
*/
public static String padRight(String orginString, String addStr, int len) {
StringBuffer strBuffer = new StringBuffer("");
if (orginString == null) {
orginString = "";
}
if (orginString.length() >= len) {
return orginString;
}
if (addStr != null) {
strBuffer.append(orginString);
while (strBuffer.length() < len) {
strBuffer.append(addStr);
}
}
return strBuffer.toString();
}

/***************************************************************************
* 将null字符串转换为0
*/
public static String NumSafe(Object strParam) {
String value = "0";
if (strParam == null) {
value = "0";
}
try {
value = String.valueOf(strParam);
} catch (Exception e) {
value = "0";
}
if (value == "null" || value.length() == 0) {
value = "0";
}
return value.trim();
}

/***************************************************************************
* 将字符串转换为Int
*/
public static int String2Int(Object argValue) {
if (isEmpty(argValue)) {
return 0;
} else {
return Integer.parseInt(String.valueOf(argValue));
}
}

/***************************************************************************
* 将字符串转换为Long
*/
public static long String2Long(Object argValue) {
if (isEmpty(argValue)) {
return 0;
} else {
return Long.parseLong(String.valueOf(argValue));
}
}

/***************************************************************************
* 格式化SQL语句
*/
public static String FormatSQLStr(String argValue) {
String returnValue = StringSafe(argValue);
if (returnValue.length() == 0) {
return "";
} else {
returnValue = returnValue.replaceAll("\"\"", "\"\"\"\"")
.replaceAll("'", "''");
}
return returnValue;
}

// public static void main(String[] args) {
// String sql="select * from sec where name='dsdf' +'and name=sfsd' ";
// System.out.println(FormatSQLStr(sql));
//
// }

/***************************************************************************
* 格式化钱四舍五入小数点后两位
*/
public static String fmtMoney(Object strParam) {
String value = "0";
if (strParam == null) {
value = "0";
}
try {
Double dblValue = Double.valueOf(strParam.toString());
if (dblValue.doubleValue() == 0) {
value = "0.00";
} else {
DecimalFormat df1 = new DecimalFormat("######.00");
value = df1.format(dblValue.doubleValue());
}
if (Double.parseDouble(value) < 1 && Double.parseDouble(value) > 0) {
value = "0" + value;
}
} catch (Exception e) {
value = "0";
}
if (value == "null" || value.length() == 0) {
value = "0";
}
return value.trim();
}

/***************************************************************************
* 将超出长度的字符串转换为...
*/
public static String trancate(String input, int len) {
StringBuffer sb = new StringBuffer(len);
int count = 0;
for (int i = 0; i < input.length(); i++) {
char c = input.charAt(i);
if (c <= '\u00ff') {
count++;
} else {
count += 2;
if (count > len) {
return sb.append(
" <font color='blue'><strong>...<strong/></font>")
.toString().trim();
}
}
sb.append(c);
if (count >= len) {
return sb.append(
" <font color='blue'><strong>...<strong/></font>")
.toString().trim();
}
}
return input;
}

/**
* 将一字符串数组以某特定的字符串作为分隔来变成字符串
*
* @since 1.0
* @param strs
*            字符串数组
* @param token
*            分隔字符串
* @return 以token为分隔的字符串
*/
public static String join(String[] strs, String token) {
if (strs == null) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < strs.length; i++) {
if (i != 0) {
sb.append(token);
}
sb.append(strs[i]);
}
return sb.toString();
}

/**
* 验证字符串合法性
*
* @since 1.0
* @param str
*            需要验证的字符串
* @param test
*            非法字符串(如:"~!#$%^&*()',;:?")
* @return true:非法;false:合法
*/
public static boolean StringCheck(String str, String test) {
if (str == null || str.equals("")) {
return false;
}
boolean flag = false;
for (int i = 0; i < test.length(); i++) {
if (str.indexOf(test.charAt(i)) != -1) {
flag = true;
break;
}
}
return flag;
}

/**
* 替换字符串
*
* @since 1.1
* @param strSc
*            需要进行替换的字符串
* @param oldStr
*            源字符串
* @param newStr
*            替换后的字符串
* @return 替换后对应的字符串
*/
public static String replace(String strSc, String oldStr, String newStr) {
String ret = strSc;
if (ret != null && oldStr != null && newStr != null) {
ret = strSc.replaceAll(oldStr, newStr);
}
return ret;
}

/**
* 替换字符串,修复java.lang.String类的replaceAll方法时第一参数是字符串常量正则时(如:"address".
* replaceAll("dd","$");)的抛出异常:java.lang.StringIndexOutOfBoundsException:
* String index out of range: 1的问题。
*
* @param strSc
*            需要进行替换的字符串
* @param oldStr
*            源字符串
* @param newStr
*            替换后的字符串
* @return 替换后对应的字符串
*/
public static String replaceAll(String strSc, String oldStr, String newStr) {
int i = -1;
while ((i = strSc.indexOf(oldStr)) != -1) {
strSc = new StringBuffer(strSc.substring(0, i)).append(newStr)
.append(strSc.substring(i + oldStr.length())).toString();
}
return strSc;
}

/**
* 将字符串转换成HTML格式的字符串
*
* @since 1.1
* @param str
*            需要进行转换的字符串
* @return 转换后的字符串
*/
public static String toHtml(String str) {
String html = StringSafe(str);
if (str == null || str.length() == 0) {
return "";
} else {
html = replace(html, "&", "&amp;");
html = replace(html, "<", "&lt;");
html = replace(html, ">", "&gt;");
html = replace(html, "\"", "&quot;");
html = replace(html, " ", "&nbsp");
html = replace(html, "\r\n", "<br>");
return html;
}
}

/**
* 将HTML格式的字符串转换成常规显示的字符串
*
* @since 1.1
* @param str
*            需要进行转换的字符串
* @return 转换后的字符串
*/
public static String toText(String str) {
String text = StringSafe(str);
if (str == null || str.length() == 0) {
return "";
} else {
text = replace(text, "&amp;", "&");
text = replace(text, "&lt;", "<");
text = replace(text, "&gt;", ">");
text = replace(text, "<br>\n", "\n");
text = replace(text, "<br>", "\n");
text = replace(text, "&quot;", "\"");
text = replace(text, "&nbsp;", " ");
return text;
}
}

public static int alphabet2No(String str) {
String[] alphabet = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
int no = 0;
for (int i = 0; i < alphabet.length; i++) {
no++;
if (str.toUpperCase().equals(alphabet[i])) {
break;
}
}
return no;
}

public static String No2alphabet(int no) {
String[] alphabet = { "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
"K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
"W", "X", "Y", "Z" };
for (int i = 0; i < alphabet.length; i++) {
if (no == i + 1) {
return alphabet[i];
}
}
return "";
}

/** 获取客户端IP */
public static String getIpAddr(HttpServletRequest request) {
String ip = request.getHeader(" x-forwarded-for ");
if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
ip = request.getHeader(" Proxy-Client-IP ");
}
if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
ip = request.getHeader(" WL-Proxy-Client-IP ");
}
if (ip == null || ip.length() == 0 || " unknown ".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
return ip;
}

/** 字符串转换 */
public static String convStr(String arg, boolean flg) {
String strWrk = "";
if (arg == null) {
arg = "";
}
if (flg) {
try {
strWrk = new String(arg.getBytes("ISO-8859-1"),
PROJECT_DEFAULT_ENCODING);
} catch (IOException e) {
strWrk = "*** ERROR convStr()";
}
} else {
strWrk = arg;
}

return strWrk;
}

/**
* 产生一定长度的随机数
*/
public static final String randomString(int length) {
Random randGen = null;
char[] numbersAndLetters = null;
Object initLock = new Object();
if (randGen == null) {
synchronized (initLock) {
if (randGen == null) {
randGen = new Random();
numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
.toCharArray();
}
}
}
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
}
return new String(randBuffer);
}

public static double add(double d1, double d2) { // 进行加法计算
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.add(b2).doubleValue();
}

public static double sub(double d1, double d2) { // 进行减法计算
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.subtract(b2).doubleValue();
}

public static double mul(double d1, double d2) { // 进行乘法计算
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.multiply(b2).doubleValue();
}

public static double div(double d1, double d2, int len) { // 进行除法计算
BigDecimal b1 = new BigDecimal(d1);
BigDecimal b2 = new BigDecimal(d2);
return b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).doubleValue();
}

public static double round(double d, int len) { // 进行四舍五入
BigDecimal b1 = new BigDecimal(d);
BigDecimal b2 = new BigDecimal(1);
return b1.divide(b2, len, BigDecimal.ROUND_HALF_UP).doubleValue();
}


/**
  * 根据输入的日期字符串 和 提前天数 ,
  * 获得 指定日期提前几天的日期对象
  * @param dateString 日期对象 ,格式如 1-31-1900
  * @param lazyDays 倒推的天数
  * @return 指定日期倒推指定天数后的日期对象
  * @throws ParseException
  */
public static Date getDate(String dateString , int beforeDays) throws ParseException{
 
  DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
  Date inputDate = dateFormat.parse(dateString);
 
  Calendar cal = Calendar.getInstance();
  cal.setTime(inputDate);
 
  int inputDayOfYear = cal.get(Calendar.DAY_OF_YEAR);
  cal.set(Calendar.DAY_OF_YEAR , inputDayOfYear-beforeDays );
 
  return cal.getTime();
}


/*
* 换算两个数的百分数
*
*/
public  static String getPercentCount(int num,int allCount) {
String result="";
if(allCount==0){
return "0"+"%";
}else{
double a= (double)num;
double b= (double)allCount;
double c = divide(a, b, 2);
result =  String.valueOf(c)+"%";
}
return result;

}
public static double divide(double v1, double v2, int scale) {

  double c = divPercent(v1, v2, scale + 2);
  // System.out.println(c+"%");
  return div(c * 100.0, 1, scale);
}
public static double divPercent(double v1, double v2, int scale) {
  if (scale < 0) {
   throw new IllegalArgumentException(
     "The scale must be a positive integer or zero");
  }
  BigDecimal b1 = new BigDecimal(Double.toString(v1));
  BigDecimal b2 = new BigDecimal(Double.toString(v2));
  return b1.divide(b2, scale, BigDecimal.ROUND_HALF_UP).doubleValue();
}

/*
* map 按照key 值排序输出其Value值
*/
public static String sortMapKeyValue(Map<String,String> map){
if (map==null) {
return "";
}
String str="";
Object[] key =  map.keySet().toArray();   
Arrays.sort(key);   
for(int i = 0; i<key.length; i++){   
//     System.out.println(map.get(key[i]));   
    str+= BaseUtil.StringSafe(map.get(key[i]));
}
return str;
}
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics