`

工具类

 
阅读更多

package com.spider.common.digitalPay.util;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.lang.reflect.Method;
import java.net.HttpURLConnection;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Map;
import java.util.Random;
import java.util.StringTokenizer;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;

/**
 * 参数配置
 *
 * @author zhough
 * @date 2013-07-03 10:57:28
 *
 */
public class StringUtils {

 /** 判断是否为double **/
 public static boolean isDouble(String value) {
  try {
   Double.parseDouble(value);
   return true;
  } catch (Exception e) {
   return false;
  }
 }

 /**
  * 检查字符串是否不为空
  *
  * @param aStr 被检查的字符串
  * @return true 字符串不为空,false 字符串为空
  */
 public static boolean isNotEmpty(String aStr) {
  return (aStr != null && aStr.trim().length() > 0);
 }

 /**
  * 检查字符串是否为空
  *
  * @param aStr
  *            被检查的字符串
  * @return true 字符串为空,false 字符串不为空
  */
 public static boolean isEmpty(String aStr) {
  return (aStr == null || aStr.trim().length() == 0);
 }

 /**
  * 判断字符串
  *
  * @param aStr
  * @return
  */
 public static String nvl(String aStr) {
  if (aStr == null || "null".equals(aStr.trim())) {
   return "";
  } else {
   return aStr.trim().toString();
  }
 }

 public static String nvl(String name, String value) {
  if (name == null || name.length() == 0) {
   return value;
  }
  return name.trim();
 }

 public static void setCookie(HttpServletResponse response, String name,
   String value, int num) {
  Cookie cookie = new Cookie(name, value);
  cookie.setPath("/");
  cookie.setMaxAge(num * 60 * 60 * 24);
  response.addCookie(cookie);
 }

 public static void setDomainCookie(HttpServletResponse response,
   String name, String value, int num) {
  Cookie cookie = new Cookie(name, value);
  cookie.setPath("/");
  cookie.setDomain(".spider.com.cn");
  cookie.setMaxAge(num * 60 * 60 * 24);
  response.addCookie(cookie);
 }

 /**
  * 获得cookies
  *
  * @param request
  * @param name
  * @return
  */
 public static String getCookie(HttpServletRequest request, String name) {
  Cookie[] cookies = request.getCookies();
  if (cookies == null) {
   return null;
  }
  for (int i = 0; i < cookies.length; ++i) {
   Cookie cookie = cookies[i];
   String cookieName = cookie.getName();
   if (cookieName.equals(name)) {
    return cookie.getValue();
   }
  }
  return null;
 }

 /**
  * 读取stringName 指定的文件内容
  *
  * @param stringName
  * @return
  * @throws IOException
  */
 public static String readFile(String failname, String decname) {
  StringBuffer sb = new StringBuffer();
  try {
   BufferedReader bufferedreader = new BufferedReader(
     new InputStreamReader(new FileInputStream(failname), "UTF-8"));
   String str;
   if ("br".equals(decname.trim())) {
    while ((str = bufferedreader.readLine()) != null) {
     sb.append(str + "\r\n");
    }
   } else {
    while ((str = bufferedreader.readLine()) != null) {
     sb.append(str);
    }
   }
   bufferedreader.close();
  } catch (IOException e) {
   Logger.error("readFile " + failname + " error = " + e.getMessage());
  }
  return sb.toString();
 }

 /**
  * 把内容输入到相应的文件中
  *
  * @param fileName
  * @param paramString2
  * @throws IOException
  */
 public static void writeFile(String filename, String name) {
  try {
   new File(filename).delete();
   FileOutputStream fos = new FileOutputStream(filename);
   fos.write(name.getBytes("UTF-8"));
   fos.close();
  } catch (IOException e) {
   Logger.error("writeFile " + filename + "--->" + name + " error = " + e.getMessage());
  }
 }

 public static String readFile_GBK(String failname) {
  StringBuffer sb = new StringBuffer();
  try {
   BufferedReader bufferedreader = new BufferedReader(
     new InputStreamReader(new FileInputStream(failname), "GB2312"));
   String s1;
   while ((s1 = bufferedreader.readLine()) != null) {
    sb.append(s1 + "\r\n");
   }
   bufferedreader.close();
  } catch (IOException e) {
   Logger.error("readFile " + failname + " error = " + e.getMessage());
  }
  return sb.toString();
 }

 public static void writeFile_GBK(String filename, String name) {
  try {
   new File(filename).delete();
   FileOutputStream fos = new FileOutputStream(filename);
   fos.write(name.getBytes("GB2312"));
   fos.close();
  } catch (IOException e) {
   Logger.error("writeFile " + filename + "--->" + name + " error = " + e.getMessage());
  }
 }

 /**
  * 字符截取 不区别中文
  *
  * @param aStr
  * @param aLen
  * @return
  */
 public static String left(String aStr, int aLen) {
  if (aLen < 0) {
   throw new IllegalArgumentException("Requested String length "
     + aLen + " is less than zero");
  }
  if ((aStr == null) || (aStr.length() <= aLen)) {
   return aStr;
  } else {
   return aStr.substring(0, aLen);
  }
 }

 /**
  * 字符截取 区别中文
  *
  * @param aStr
  * @param aLen
  * @return
  */
 public static String leftChar(String aStr, int aLen) {
  String results = "";
  if (StringUtils.isNotEmpty(aStr)) {
   char chars[] = aStr.toCharArray();
   int num = 0;
   for (int i = 0; i < chars.length; i++) {
    String tmpStr = "";
    if (Character.toString(chars[i]).matches("[\\u4E00-\\u9FA5]+")) {
     tmpStr = Character.toString(chars[i]);
     num += 2;
    } else {
     tmpStr = Character.toString(chars[i]);
     num += 1;
    }
    results += tmpStr;
    if (num >= aLen) {
     break;
    }
   }
  }
  return results;
 }

 /**
  * 将字符串stringName 根据标记splitStringName拆分为字符数组
  *
  * @param stringName
  * @param sign
  * @return
  */
 public static String[] split(String name, String sign) {
  if (name == null || name.length() == 0) {
   return new String[0];
  }
  if (name.indexOf(sign) < 0) {
   return new String[] { name };
  }
  // StringTokenizer 类允许应用程序将字符串分解为标记 为指定字符串构造一个 StringTokenizer
  StringTokenizer stkr = new StringTokenizer(name, sign);
  // 计算在生成异常之前可以调用此 tokenizer 的 nextToken 方法的次数
  int amount = stkr.countTokens();
  String[] as = new String[amount];
  for (int i = 0; i < amount; ++i) {
   // 返回此 StringTokenizer 的下一个标记 赋值
   as[i] = stkr.nextToken();
  }
  return as;
 }

 @SuppressWarnings("unused")
 private static Object getFieldValueByName(String fieldName, Object obj) {
  try {
   String Letter = fieldName.substring(0, 1).toUpperCase();
   String methodStr = "get" + Letter + fieldName.substring(1);
   Method method = obj.getClass().getMethod(methodStr, new Class[] {});
   Object value = method.invoke(obj, new Object[] {});
   return value;
  } catch (Exception e) {
   return null;
  }
 }

 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("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.getHeader("HTTP_CLIENT_IP");
      if (ip == null || ip.length() == 0
        || "unknown".equalsIgnoreCase(ip)) {
       ip = request.getHeader("HTTP_X_FORWARDED_FOR");
       if (ip == null || ip.length() == 0
         || "unknown".equalsIgnoreCase(ip)) {
        ip = request.getRemoteAddr();
       }
      }
     }
    }
   }
  }
  /** 如果ip来源是负载均衡设备 则 使用clientip获取值 */
  if (null == ip || "192.168.10.1".equals(ip)) {
   ip = request.getHeader("client-ip");
   if (null == ip) {
    ip = request.getRemoteAddr();
   }
  }
  return ip;
 }

 /**
  * 判断文件是否存在
  *
  * @param filename
  *            配置文件的路径名
  *
  * @author songnan
  * @Date 2009-08-04
  * @return
  */
 public static boolean exists(String filename) {
  return new File(filename).exists();
 }

 /**
  *
  * @param db
  * @return 3.00
  */
 public static String Decimalformat(double db) {
  DecimalFormat df1 = new DecimalFormat("###,##0.00");
  return df1.format(db);
 }

 /**
  * 对Double 进行 format为 0.00
  *
  * @param paramString
  * @return
  */
 public static String formatdb(double paramDouble) {
  DecimalFormat df = new DecimalFormat("#0.00");
  return df.format(paramDouble);
 }

 /**
  * 对String 进行 format为 0.00
  *
  * @param paramString
  * @return
  */
 public static String formatstr(String paramString) {
  DecimalFormat df = new DecimalFormat("#0.00");
  if (isNotEmpty(paramString)) {
   return df.format(Double.valueOf(paramString));
  } else {
   return "0.00";
  }
 }

 public static String formatstrint(String paramString) {
  DecimalFormat df = new DecimalFormat("#0");
  if (isNotEmpty(paramString)) {
   return df.format(Double.valueOf(paramString));
  } else {
   return "0.00";
  }
 }

 /**
  *
  * @param db
  * @return 3.00
  */
 public static String DecimalformatStr(String str) {
  if ("".equals(nvl(str))) {
   return "";
  }
  return Decimalformat(Double.parseDouble(str));
 }

 /**
  * 日期格式转换
  *
  * @param dateStr
  * @param type
  *            转换的类型
  * @return
  */
 public static String Dateformat(String dateStr, String type) {
  try {
   SimpleDateFormat dateFormatter = new SimpleDateFormat(type);
   if ("".equals(nvl(dateStr))) {
    return "";
   }
   Date date = dateFormatter.parse(dateStr);
   return dateFormatter.format(date);
  } catch (ParseException e) {
   e.printStackTrace();
   return "";
  }
 }

 /**
  * 日期格式转换
  *
  * @param dateStr
  * @param type
  *            转换的类型
  * @return
  */
 public static String DateformatByType(String dateStr, String type) {
  try {
   SimpleDateFormat dateFormatter = new SimpleDateFormat(type);
   if ("".equals(nvl(dateStr))) {
    return "";
   }
   Date date = strToDate(dateStr);
   return dateFormatter.format(date);
  } catch (Exception e) {
   e.printStackTrace();
   return "";
  }
 }

 public static double strToDb(String str) {
  if ("".equals(nvl(str))) {
   return 0;
  } else {
   return Double.parseDouble(str);
  }
 }

 public static int strToInt(String str) {
  if ("".equals(nvl(str))) {
   return 0;
  } else {
   return Integer.parseInt(str);
  }
 }

 /**
  * 获取当天时间
  *
  * @param dateformat
  * @return
  */
 public static String getNowTime(String dateformat) {
  Date now = new Date();
  SimpleDateFormat dateFormat = new SimpleDateFormat(dateformat);
  String hehe = dateFormat.format(now);
  return hehe;
 }

 /** 几小时之后的时间 * */
 public static String getPassHourTime(int passHour) {
  SimpleDateFormat sdf = new SimpleDateFormat("HHmm");
  Calendar cal = new GregorianCalendar();
  cal.setTime(new Date());
  cal.add(Calendar.HOUR, passHour);
  Date dateTime = cal.getTime();
  String preHour = sdf.format(dateTime);
  return preHour;
 }

 /**
  * 根据date 相加 后的年 月 日
  *
  * @param date
  * @return
  */
 public static String getaddDate(int date) {
  GregorianCalendar currentDate = new GregorianCalendar();
  currentDate.add(GregorianCalendar.DATE, date);
  Date monday = currentDate.getTime();
  SimpleDateFormat sdf = new SimpleDateFormat("yyyyMM");
  Calendar cal = new GregorianCalendar();
  cal.setTime(monday);
  cal.add(Calendar.MONTH, 1);
  cal.set(Calendar.DATE, 1);
  Date yearDay = cal.getTime();
  String preMonday = sdf.format(yearDay);
  return preMonday;
 }

 // 根据日期 date 获得向后推迟day个月的最后一天
 @SuppressWarnings("deprecation")
 public static String getendDateTow(String date, int month) {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMM");
  String newDate = null;
  try {
   Date newdate = myFormatter.parse(date);
   Calendar cal = new GregorianCalendar();
   cal.setTime(newdate);
   int i = cal.getTime().getMonth() + 1;
   if ((i + 1) % 2 == 0) {
    cal.add(Calendar.MONTH, month);
   } else {
    cal.add(Calendar.MONTH, month + 1);
   }
   cal.add(Calendar.DATE, -1);// 减去一天,变为当月最后一天
   Date dateTime = cal.getTime();
   newDate = myFormatter.format(dateTime);
  } catch (Exception e) {
   e.getMessage();
  }
  return newDate;
 }

 @SuppressWarnings("deprecation")
 public static String getendDateThree(String date, int month) {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMM");
  String newDate = null;
  try {
   Date newdate = myFormatter.parse(date);
   Calendar cal = new GregorianCalendar();
   cal.setTime(newdate);
   int i = cal.getTime().getMonth() + 1;
   if ((i - 1) % 3 == 0) {
    cal.add(Calendar.MONTH, month);
   } else if ((i - 2) % 3 == 0) {
    cal.add(Calendar.MONTH, month + 2);
   } else {
    cal.add(Calendar.MONTH, month + 1);
   }
   cal.add(Calendar.DATE, -1);// 减去一天,变为当月最后一天
   Date dateTime = cal.getTime();
   newDate = myFormatter.format(dateTime);
  } catch (Exception e) {
   e.getMessage();
  }
  return newDate;
 }

 @SuppressWarnings("deprecation")
 public static String getendDateSix(String date, int month) {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMM");
  String newDate = null;
  try {
   Date newdate = myFormatter.parse(date);
   Calendar cal = new GregorianCalendar();
   cal.setTime(newdate);
   int i = cal.getTime().getMonth() + 1;
   if (0 < i && i <= 1) {
    cal.set(Calendar.MONTH, 0);
   } else if (i > 1 && i <= 7) {
    cal.set(Calendar.MONTH, 6);
   } else {
    cal.add(Calendar.YEAR, 1);
    cal.set(Calendar.MONTH, 0);
   }
   Date dateTime = cal.getTime();
   newDate = myFormatter.format(dateTime);
  } catch (Exception e) {
   e.getMessage();
  }
  return newDate;
 }

 // 根据日期 date 获得向后推迟day个月的最后一天
 public static String getendDate(String date, int month) {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMM");
  String newDate = null;
  try {
   Date newdate = myFormatter.parse(date);
   Calendar cal = new GregorianCalendar();
   cal.setTime(newdate);
   cal.add(Calendar.MONTH, month);
   cal.add(Calendar.DATE, -1);// 减去一天,变为当月最后一天
   Date dateTime = cal.getTime();
   newDate = myFormatter.format(dateTime);
  } catch (Exception e) {
   e.getMessage();
  }
  return newDate;
 }

 public static String getCurrDate() {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMM");
  Date dDate = new Date();
  String strTime = myFormatter.format(dDate);
  return strTime;
 }

 // 获取当前年份的最后一个月
 public static String getlastMonthDate() {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyyMM");
  Date dDate = new Date();
  String strTime = myFormatter.format(dDate);
  String newDate = strTime.substring(0, 4) + "12";
  return newDate;
 }

 /**
  * 从XML文件xmlName中提取包含XML标记attributeName的内容
  *
  * @param xmlName
  * @param attributeName
  * @return
  */
 public static String parseXMLTag(String xmlName, String attributeName) {
  String attributeNameOne = "<" + attributeName + ">";
  String attributeNameTwo = "</" + attributeName + ">";
  int i = xmlName.indexOf(attributeNameOne);
  int j = xmlName.indexOf(attributeNameTwo);
  if ((i < 0) || (j < 0)) {
   return "";
  }
  return nvl(xmlName.substring(i + attributeNameOne.length(), j));
 }

 public static String jumpLogin(String jump_login) {
  if (StringUtils.isNotEmpty(jump_login)) {
   jump_login = StringUtils.nvl(jump_login);
   if ("orderdelivery".equals(jump_login)) {
    return "orderdelivery";
   }
  }
  return "login";
 }

 public static String format(int i) {
  String seq = "000000" + String.valueOf(i);
  seq = seq.substring(seq.length() - 3);
  return seq;
 }

 public static String replaceStr(String str) {
  if (str.contains("/")) {
   str = str.replaceAll("/", "\\\\");
  }
  if (str.contains("|")) {
   str = str.replaceAll("\\|", "\\\\");
  }
  return str;
 }

 public static String replace(String str, String name, String value) {
  if (str == null || str.length() == 0) {
   return "";
  }
  if ((name == null) || (value == null) || (name.length() == 0)
    || (value.length() == 0)) {
   return str;
  }

  StringBuffer sb = new StringBuffer();
  int i = 0;
  for (int j = str.indexOf(name, i); j >= 0; j = str.indexOf(name, i)) {
   sb.append(str.substring(i, j));
   sb.append(value);
   i = j + name.length();
  }
  sb.append(str.substring(i));
  return sb.toString();
 }

 public static String zpf(String param, int num) {
  String str = "000000000000" + param;
  return str.substring(str.length() - num);
 }

 /**
  * 随机获取
  *
  * @author songnan
  * @param digit
  * @return
  */
 public static String getRandomString(int digit) {
  StringBuffer str = new StringBuffer(digit);
  for (int i = 0; i < digit; i++) {
   int psd = (int) (Math.random() * (26 * 2 + 10));
   if (psd >= 26 + 10) { // a~z
    char a = (char) (psd + 97 - 10 - 26);
    str.append(String.valueOf(a));
   } else if (psd >= 10) { // A~Z
    char a = (char) (psd + 65 - 10);
    str.append(String.valueOf(a));
   } else { // 0~9
    str.append(String.valueOf(psd));
   }
  }
  return str.toString().toLowerCase();
 }

 /**
  * 判断是否是邮箱
  *
  * @author songnan
  * @param emil
  * @return
  */
 public static boolean checkemail(String emil) {
  Pattern pattern = Pattern
    .compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");
  Matcher isNum = pattern.matcher(emil);
  if (!isNum.matches()) {
   return false;
  }
  return true;
 }

 /**
  * 用正则表达式 判断是否数字
  *
  * @author songnan
  * @param str
  * @return
  */
 public static boolean isNumeric(String str) {
  if (StringUtils.isEmpty(str)) {
   return false;
  } else {
   Pattern pattern = Pattern.compile("[0-9]*");
   return pattern.matcher(str).matches();
  }
 }

 /**
  * 编码转换
  *
  * @author songnan
  * @param name
  * @return
  */
 public static String Transcoding(String name) {
  if ((name == null) || (name.length() == 0))
   return name;
  try {
   if (name.getBytes("ISO-8859-1").length > 1) {
    return new String(name.getBytes("ISO-8859-1"), "UTF-8");
   }
  } catch (Exception exception) {
  }
  return name;
 }

 /**
  * 创建目录
  *
  * @author songnan
  * @param destDirName
  * @return
  */
 public static boolean createDir(String destDirName) {
  File dir = new File(destDirName);
  if (dir.exists()) {
   return false;
  }
  if (!destDirName.endsWith(File.separator)) {
   destDirName = destDirName + File.separator;
  }
  if (dir.mkdirs()) {
   return true;
  } else {
   return false;
  }
 }

 /**
  * 基本功能:过滤所有以"<"开头以">"结尾的标签
  *
  * @author songnan
  * @param str
  * @return String
  */
 public static String filterHtml(String str) {
  Pattern pattern = Pattern.compile("<([^>]*)>");
  Matcher matcher = pattern.matcher(str);
  StringBuffer sb = new StringBuffer();
  boolean result1 = matcher.find();
  while (result1) {
   matcher.appendReplacement(sb, "");
   result1 = matcher.find();
  }
  matcher.appendTail(sb);
  return sb.toString();
 }

 public static String digit(String str) {
  if (isEmpty(str)) {
   return "";
  }
  String result = "";
  for (int i = 0; i <= str.length() - 1; i++) {
   char c = str.charAt(i);
   switch (c) {
   case '1':
    result += "一";
    break;
   case '2':
    result += "二";
    break;
   case '3':
    result += "三";
    break;
   case '4':
    result += "四";
    break;
   case '5':
    result += "五";
    break;
   case '6':
    result += "六";
    break;
   case '7':
    result += "七";
    break;
   case '8':
    result += "八";
    break;
   case '9':
    result += "九";
    break;
   case '0':
    break;
   }
  }
  return result;
 }

 /**
  * 日期格式转换
  *
  * @param dateStr
  * @param type
  *            转换的类型
  * @return
  */
 public static String Dateformat(String dateStr) {
  String pattern = "yyyy-MM-dd HH:mm:ss";
  try {
   if (StringUtils.isEmpty(dateStr)) {
    return "";
   }
   if (!dateStr.contains(":")) {
    pattern = "yyyy-MM-dd";
   }
   SimpleDateFormat dateFormatter = new SimpleDateFormat(pattern);
   if (StringUtils.isEmpty(dateStr)) {
    return "";
   }
   Date date = dateFormatter.parse(dateStr);
   return dateFormatter.format(date);
  } catch (Exception e) {
   e.printStackTrace();
   return "";
  }
 }

 public static String cDateformatMonth(String dateStr) {
  if (StringUtils.isNotEmpty(dateStr)) {
   String pattern = "MM月dd日";
   SimpleDateFormat dateFormatter = new SimpleDateFormat(pattern);
   SimpleDateFormat dateFormatters = new SimpleDateFormat("yyyy-MM-dd");
   try {
    return dateFormatter.format(dateFormatters.parse(dateStr));
   } catch (ParseException e) {
    e.printStackTrace();
   }
  }
  return "";
 }
 
 public static String DateformatYY(String dateStr) {
  if (StringUtils.isNotEmpty(dateStr)) {
   String pattern = "yyyy年MM月dd日";
   SimpleDateFormat dateFormatter = new SimpleDateFormat(pattern);
   SimpleDateFormat dateFormatters = new SimpleDateFormat("yyyy-MM-dd");
   try {
    return dateFormatter.format(dateFormatters.parse(dateStr));
   } catch (ParseException e) {
    e.printStackTrace();
   }
  }
  return "";
 }
 
 public static String cDateformatHour(String dateStr) {
  String pattern = "HH:mm";
  SimpleDateFormat dateFormatter = new SimpleDateFormat(pattern);
  SimpleDateFormat dateFormatters = new SimpleDateFormat("HH:mm");
  try {
   return dateFormatter.format(dateFormatters.parse(dateStr));
  } catch (ParseException e) {
   e.printStackTrace();
  }
  return null;
 }

 public static String RandomStrNum(int num) {
  StringBuffer randomCode = new StringBuffer();
  char codeSequence[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
    '9' };
  Random random = new Random();
  for (int i = 0; i < num; i++) {
   String strRand = String.valueOf(codeSequence[random
     .nextInt(codeSequence.length)]);
   randomCode.append(strRand);
  }
  return randomCode.toString();
 }

 public static String RandomStr(int num) {
  StringBuffer randomCode = new StringBuffer();
  char codeSequence[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
    '9', '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' };
  Random random = new Random();
  for (int i = 0; i < num; i++) {
   String strRand = String.valueOf(codeSequence[random
     .nextInt(codeSequence.length)]);
   randomCode.append(strRand);
  }
  return randomCode.toString();
 }

 /**
  * 根据一个日期,返回是星期几的字符串
  *
  * @param sdate
  * @return
  */
 public static String getWeek(String sdate) {
  if (StringUtils.isNotEmpty(sdate)) {
   // 再转换为时间
   Date date = strToDate(sdate);
   Calendar c = Calendar.getInstance();
   c.setTime(date);
   // int hour=c.get(Calendar.DAY_OF_WEEK);
   // hour中存的就是星期几了,其范围 1~7
   // 1=星期日 7=星期六,其他类推
   return new SimpleDateFormat("EEEE").format(c.getTime());
  }
  return "";
 }

 public static Date strToDate(String strDate) {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  ParsePosition pos = new ParsePosition(0);
  Date strtodate = formatter.parse(strDate, pos);
  return strtodate;
 }

 public static Date strToDateTime(String strDate) {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
  ParsePosition pos = new ParsePosition(0);
  Date strtodate = formatter.parse(strDate, pos);
  return strtodate;
 }

 public static String resultError(String parm, String messages) {
  String result = "";
  if ("1".equals(parm)) {
   result = "锁位失败";
  } else if ("2".equals(parm)) {
   result = "座椅维修,请另择";
  } else if ("3".equals(parm)) {
   if (messages.contains("SLPE:Seat-Locking Processing Error")) {
    result = "座位无法锁定,可能已被他人选择";
   } else {
    result = "查无此座";
   }
  } else if ("4".equals(parm)) {
   if (messages.contains("NECSE:Not Enough Continuous Seats Error")) {
    result = "没有足够的连续座位";
   } else {
    result = "情侣座锁定失败";
   }
  } else if ("5".equals(parm)) {
   result = "数据链路断开(检查影院网络连接)";
  } else if ("6".equals(parm)) {
   result = "场次信息无效";
  } else if ("7".equals(parm)) {
   result = "";
  } else if ("8".equals(parm)) {
   result = "";
  } else if ("9".equals(parm)) {
   result = "";
  } else if ("10".equals(parm)) {
   result = "日期区间超过2天";
  } else if ("11".equals(parm)) {
   result = "锁位失败,每次允许提交[x]个锁位请求";
  } else if ("12".equals(parm)) {
   result = "超过每笔订单最大锁位数6个";
  } else if ("13".equals(parm)) {
   result = "不能锁定已开场的场次";
  } else {
   return messages;
  }
  return result;
 }

 public static String getToken(String token) {
  return StringUtils.getNowTime("yyyyMMddHHmmss") + token;
 }

 public static int getWeekInt(String sdate) {
  Calendar c = Calendar.getInstance();
  c.setTime(getDate(sdate));
  return c.get(Calendar.DAY_OF_WEEK) - 1;
 }

 public static Date getDate(String sdate) {
  SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
  ParsePosition pos = new ParsePosition(0);
  return formatter.parse(sdate, pos);
 }

 public static int getTwoDay(String sj1, String sj2) {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd");
  long day = 0;
  try {
   java.util.Date date = myFormatter.parse(sj1);
   java.util.Date mydate = myFormatter.parse(sj2);
   day = (date.getTime() - mydate.getTime()) / (24 * 60 * 60 * 1000);
  } catch (Exception e) {
   return 0;
  }
  return (int) day;
 }

 public static long getTwoDate(String sj1, String sj2) {
  SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
  long day = 0;
  try {
   java.util.Date date = myFormatter.parse(sj1);
   java.util.Date mydate = myFormatter.parse(sj2);
   day = date.getTime() - mydate.getTime();
  } catch (Exception e) {
   return 0;
  }
  return day;
 }

 public static long getTwoTime(String sj1, String sj2) {
  SimpleDateFormat myFormatter = new SimpleDateFormat(
    "yyyy-MM-dd HH:mm:ss");
  long day = 0;
  try {
   java.util.Date date = myFormatter.parse(sj1);
   java.util.Date mydate = myFormatter.parse(sj2);
   day = date.getTime() - mydate.getTime();
  } catch (Exception e) {
   return 0;
  }
  return day;
 }

 public static boolean writeTxtFile(String newStr, String url) {
  FileInputStream fis = null;
  InputStreamReader isr = null;
  BufferedReader br = null;
  FileOutputStream fos = null;
  PrintWriter pw = null;
  try {
   File file = new File(url);
   if (!file.exists()) {
    file.createNewFile();
   }
   fis = new FileInputStream(file);
   isr = new InputStreamReader(fis);
   br = new BufferedReader(isr);
   StringBuffer buf = new StringBuffer();
   String readTmp = "";
   for (int j = 1; (readTmp = br.readLine()) != null; j++) {
    buf = buf.append(readTmp);
    buf = buf.append(System.getProperty("line.separator"));
   }
   buf.append(newStr + "\r\n");
   fos = new FileOutputStream(file);
   pw = new PrintWriter(fos);
   pw.write(buf.toString().toCharArray());
   pw.flush();
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  } finally {
   try {
    if (pw != null) {
     pw.close();
    }
    if (fos != null) {
     fos.close();
    }
    if (br != null) {
     br.close();
    }
    if (isr != null) {
     isr.close();
    }
    if (fis != null) {
     fis.close();
    }
   } catch (Exception e1) {
    e1.printStackTrace();
   }
  }
  return true;
 }

 public static boolean writeXmlFile(String newStr, String url) {
  FileInputStream fis = null;
  InputStreamReader isr = null;
  BufferedReader br = null;
  FileOutputStream fos = null;
  PrintWriter pw = null;
  try {
   File file = new File(url);
   if (file.exists()) {
    file.delete();
   }
   file.createNewFile();
   fis = new FileInputStream(file);
   isr = new InputStreamReader(fis);
   br = new BufferedReader(isr);
   StringBuffer buf = new StringBuffer();
   String readTmp = "";
   for (int j = 1; (readTmp = br.readLine()) != null; j++) {
    buf = buf.append(readTmp);
    buf = buf.append(System.getProperty("line.separator"));
   }
   buf.append(newStr + "\r\n");
   fos = new FileOutputStream(file);
   pw = new PrintWriter(fos);
   pw.write(buf.toString().toCharArray());
   pw.flush();
  } catch (Exception e) {
   e.printStackTrace();
   return false;
  } finally {
   try {
    if (pw != null) {
     pw.close();
    }
    if (fos != null) {
     fos.close();
    }
    if (br != null) {
     br.close();
    }
    if (isr != null) {
     isr.close();
    }
    if (fis != null) {
     fis.close();
    }
   } catch (Exception e1) {
    e1.printStackTrace();
   }
  }
  return true;
 }

 /** 将分钟转化为xx小时xx分钟 * */
 public static String getHours(String second) {
  int duration = StringUtils.strToInt(second);
  String durationTime = "";
  if (duration >= 60) {
   int hour = duration / 60;
   durationTime = hour + "小时";
   if ((duration - hour * 60) > 0) {
    durationTime += (duration - hour * 60) + "分钟";
   }
  } else {
   durationTime = duration + "分钟";
  }
  return durationTime;
 }

 /** 手机客户端特殊字符替换 * */
 public static String getReplaceResult(String message) {
  return message.replaceAll("\r\n", "").replaceAll("\"", "“");
 }

 /**
  * 根据经纬度 获取范围 lat 纬度 lon 经度
  *
  * @param raidus
  *            单位米 return minLat,minLng,maxLat,maxLng
  */
 public static double[] getAround(double lat, double lon, int raidus) {

  Double latitude = lat;
  Double longitude = lon;

  Double degree = (24901 * 1609) / 360.0;
  double raidusMile = raidus;

  Double dpmLat = 1 / degree;
  Double radiusLat = dpmLat * raidusMile;
  Double minLat = latitude - radiusLat;
  Double maxLat = latitude + radiusLat;

  Double mpdLng = degree * Math.cos(latitude * (Math.PI / 180));
  Double dpmLng = 1 / mpdLng;
  Double radiusLng = dpmLng * raidusMile;
  Double minLng = longitude - radiusLng;
  Double maxLng = longitude + radiusLng;
  return new double[] { minLat, minLng, maxLat, maxLng };
 }

 /**
  * 获取传过来的流媒体
  *
  * @param request
  * @return
  * @throws UnsupportedEncodingException
  * @throws IOException
  */
 public static String getRequestData(HttpServletRequest request)
   throws UnsupportedEncodingException, IOException {
  String encode = "utf-8";
  BufferedReader in = new BufferedReader(new InputStreamReader(request
    .getInputStream(), encode));

  String result = "";
  String line;
  while ((line = in.readLine()) != null) {
   result = result + line;
  }
  in.close();
  return result;
 }

 private final static String regxpForHtml = "<([^>]*)>"; // 过滤所有以<开头以>结尾的标签

 /**
  * 默认去掉<> 标签, strs 需要过滤的字符数组
  *
  * @param str
  * @param strs
  * @return
  */
 public static String filterHtml(String str, String[] strs) {
  Pattern pattern = Pattern.compile(regxpForHtml);
  Matcher matcher = pattern.matcher(str);
  StringBuffer sb = new StringBuffer();
  boolean result1 = matcher.find();
  while (result1) {
   matcher.appendReplacement(sb, "");
   result1 = matcher.find();
  }
  matcher.appendTail(sb);
  String result = sb.toString();
  for (int i = 0; i < strs.length; i++) {
   result = result.replace(strs[i], "");
  }
  return result;
 }

 /** 读取对方地址输出的流媒体 * */
 public static String dataReq(String urlLink, String xml, String encode) {
  HttpURLConnection httpurlconnection = null;
  try {
   URL url = null;
   url = new URL(urlLink);
   httpurlconnection = (HttpURLConnection) url.openConnection();
   // httpurlconnection.setRequestProperty("Content-type", "text/xml");
   httpurlconnection.setDoOutput(true);
   httpurlconnection.setDoInput(true);
   httpurlconnection.setRequestMethod("POST");
   if (isNotEmpty(xml)) {
    String SendData = xml;
    httpurlconnection.getOutputStream().write(
      SendData.getBytes(encode));
    httpurlconnection.getOutputStream().flush();
    httpurlconnection.getOutputStream().close();
   }
   String result = "";
   BufferedReader in = new BufferedReader(new InputStreamReader(
     httpurlconnection.getInputStream(), encode));
   String line;
   while ((line = in.readLine()) != null) {
    result = result + line + "\r\n";
   }
   in.close();
   return result;
  } catch (Exception e) {
   e.printStackTrace();
   return "";
  } finally {
   if (httpurlconnection != null)
    httpurlconnection.disconnect();
  }
 }

 /** 读取对方地址输出的流媒体 * */
 public static String dataReqGET(String urlLink, String xml, String encode) {
  HttpURLConnection httpurlconnection = null;
  try {
   URL url = null;
   url = new URL(urlLink);
   httpurlconnection = (HttpURLConnection) url.openConnection();
   // httpurlconnection.setRequestProperty("Content-type", "text/xml");
   httpurlconnection.setDoOutput(true);
   httpurlconnection.setDoInput(true);
   httpurlconnection.setRequestMethod("GET");// POST or GET
   if (isNotEmpty(xml)) {
    String SendData = xml;
    httpurlconnection.getOutputStream().write(
      SendData.getBytes(encode));
    httpurlconnection.getOutputStream().flush();
    httpurlconnection.getOutputStream().close();
   }
   String result = "";
   BufferedReader in = new BufferedReader(new InputStreamReader(
     httpurlconnection.getInputStream(), encode));
   String line;
   while ((line = in.readLine()) != null) {
    result = result + line + "\r\n";
   }
   in.close();
   return result;
  } catch (Exception e) {
   e.printStackTrace();
   return "";
  } finally {
   if (httpurlconnection != null)
    httpurlconnection.disconnect();
  }
 }

 /**
  * 获取URL主域名
  *
  * @param url
  * @return
  */
 public static String getRealmname(String url) {
  Pattern p = Pattern.compile(
    "(?<=http://|\\.)[^.]*?\\.(com|cn|net|org|biz|info|cc|tv)",
    Pattern.CASE_INSENSITIVE);
  Matcher matcher = p.matcher(url);
  matcher.find();
  return matcher.group();
 }
 
 /**
  * @param url 请求远程地址
  * @return
  */
 public static String readContentFromGet(String url) {
  StringBuffer receivedData = new StringBuffer();
  try{
   URL getUrl = new URL(url);
         HttpURLConnection connection = (HttpURLConnection) getUrl.openConnection();
         connection.setRequestProperty("User-Agent","Mozilla/4.0 (compatible; MSIE 5.0; Windows XP; DigExt)");
         connection.setDoInput(true);
         connection.setDoOutput(true);
         connection.connect();
         BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream(),"UTF-8"));
        
         String aLine = null;
         while ((aLine = reader.readLine()) != null)
    receivedData.append(aLine.trim());
         reader.close();
         connection.disconnect();
  }catch(IOException e){
   e.printStackTrace();
  }
        return receivedData.toString();
    }
 
 /** 获取两个日期相差的天数 **/
 public static long getQuot(String time1, String time2){ 
  long quot = 0; 
  SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd"); 
  try {  
   Date date1 = ft.parse( time1 );  
   Date date2 = ft.parse( time2 );  
   quot = date1.getTime() - date2.getTime();  
   quot = quot / 1000 / 60 / 60 / 24; 
  } catch (ParseException e) {  
   e.printStackTrace(); 
  } 
  return quot;
 }
 
 /** 比较两个日期的大小 **/
 public static boolean compareDate(String time1, String time2){
  boolean b = false;
  SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd"); 
  try{
   Date date1 = ft.parse( time1 );  
   Date date2 = ft.parse( time2 );
   if(date1.getTime() > date2.getTime()){
    b = true;
   }
  }catch(ParseException e){
   e.printStackTrace(); 
  }
  return b;
 }
 
 /** 比较两个日期的大小 **/
 public static boolean compareDate1(String time1, String time2){
  boolean b = false;
  SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd"); 
  try{
   Date date1 = ft.parse( time1 );  
   Date date2 = ft.parse( time2 );
   if(date1.getTime() >= date2.getTime()){
    b = true;
   }
  }catch(ParseException e){
   e.printStackTrace(); 
  }
  return b;
 }
 
 /** 日期加月数 **/
 public static String getLateDate(String sDate,int iMonths) { 
  String sLateDate = ""; 
  Calendar calendar = Calendar.getInstance(); 
  try {  
   String time = sDate;  
   String[] arrDate = time.split("-");  
   int iYear = Integer.valueOf(arrDate[0]);  
   int iMonth = Integer.valueOf(arrDate[1]);  
   int iDay = Integer.valueOf(arrDate[2]);      
   calendar.set(iYear, iMonth, iDay);  
   calendar.add(Calendar.MONTH, -1);//因为Month值从0开始,所以取得的值应该减去1  
   calendar.add(Calendar.MONTH, iMonths);     
   Date date = new Date();  
   SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");//构造日期格式化器  
   date = calendar.getTime();  
   sLateDate = sdf.format(date); 
  } catch (Exception e) {  
   e.printStackTrace(); 
  } 
  return sLateDate;
 }
}

分享到:
评论

相关推荐

    java sql操作工具类 java sql操作工具类

    java sql操作工具类 java sql操作工具类java sql操作工具类 java sql操作工具类java sql操作工具类 java sql操作工具类java sql操作工具类 java sql操作工具类java sql操作工具类 java sql操作工具类java sql操作...

    java 获取地址工具类 java 获取地址工具类

    java 获取地址工具类 java 获取地址工具类java 获取地址工具类 java 获取地址工具类java 获取地址工具类 java 获取地址工具类java 获取地址工具类 java 获取地址工具类java 获取地址工具类 java 获取地址工具类java ...

    java 转义和反转义工具类 java 转义和反转义工具类

    java 转义和反转义工具类 java 转义和反转义工具类java 转义和反转义工具类 java 转义和反转义工具类java 转义和反转义工具类 java 转义和反转义工具类java 转义和反转义工具类 java 转义和反转义工具类java 转义和...

    java sql 工具类 java sql 工具类 java sql 工具类

    java sql 工具类 java sql 工具类 java sql 工具类java sql 工具类 java sql 工具类 java sql 工具类java sql 工具类 java sql 工具类 java sql 工具类java sql 工具类 java sql 工具类 java sql 工具类java sql ...

    C++工具类-常用工具类源码

    在C++编程中,工具类是非常重要的一部分,它们提供了一系列通用功能,可以帮助开发者更高效地进行项目开发。本文将深入探讨标题"**C++工具类-常用工具类源码**"所涵盖的知识点,主要围绕文件处理、编码处理、字符串...

    Rabbitmq工具类,java工具类RabbitmqUtil

    `RabbitmqUtil` 是一个专门为Java开发者设计的工具类,简化了与RabbitMQ交互的复杂过程,使得开发者能够更快速、更方便地发送和接收消息。 首先,我们来详细了解一下`RabbitmqUtil`工具类的主要功能: 1. **连接...

    java ID生成器工具类 java ID生成器工具类

    java ID生成器工具类 java ID生成器工具类java ID生成器工具类 java ID生成器工具类java ID生成器工具类 java ID生成器工具类java ID生成器工具类 java ID生成器工具类java ID生成器工具类 java ID生成器工具类java ...

    自己整理的C#常用工具类

    在C#编程中,工具类(Utility Class)是一种常见的设计模式,它封装了一些常用的功能,以便在项目中方便地重复使用。这些工具类通常包含静态方法,不涉及实例化,直接通过类名调用,降低了代码冗余,提高了代码复用...

    Elasticsearch工具类

    Elasticsearch工具类是开发中常见的一种抽象封装,旨在简化与Elasticsearch数据库的交互,提高代码的可读性和可维护性。Elasticsearch是一种基于Lucene的分布式、RESTful搜索和分析引擎,广泛用于实时大数据分析和...

    C#工具类库类库 包含所有的常用工具类

    在C#编程中,工具类库是开发人员经常会用到的一种资源,它们提供了一系列预定义的方法和功能,以便简化各种常见的编程任务。标题中的"C#工具类库类库 包含所有的常用工具类"暗示了这是一个集合,包含了多种实用工具...

    Android快速开发系列 10个常用工具类 程序源码

    在Android应用开发中,工具类(Utils)是程序员经常使用的辅助模块,它们包含了一系列静态方法,用于处理各种常见的任务,从而提高代码的复用性和可维护性。本资源"Android快速开发系列 10个常用工具类 程序源码...

    超实用的android自定义log日志输出工具类

    android自定义log日志输出工具,该工具类具有以下优点: 1 在LogUtlis方法的第一个参数中填this可以输出当前类的名称,特别是在匿名内部类使用也可以输出当前类名。 如 : LogUtils.i(this,”这是一个实用的日志...

    C# Util 实用工具类

    C# Util中的Json工具类通常提供了序列化和反序列化JSON对象的方法,如将C#对象转换为JSON字符串,或者将JSON字符串解析为C#对象,这在处理API请求或保存配置文件时非常有用。 2. **Net**: 这部分可能包含网络通信...

    jaava和jsp工具类

    [工具类] 获得汉字拼音首字母的java工具类 .java [工具类] 获取绝对路径 .java [工具类] 记录log日志文件的工具类 .java [工具类] 连接数据库的工具类 .java [工具类] 使用Java程序来实现HTTP文件的队列下载 ....

    小程序源码 小工具类(带后台)

    小程序源码 小工具类(带后台)小程序源码 小工具类(带后台)小程序源码 小工具类(带后台)小程序源码 小工具类(带后台)小程序源码 小工具类(带后台)小程序源码 小工具类(带后台)小程序源码 小工具类(带...

    Java开发工具类

    Class类工具 \Cookie工具类 \excel读取 工具类\Java如何生成验证码图片和点击刷新验证码\java获取当前月第一天和最后一天,上个月第一天和最后一天\java实现ftp文件的上传与下载\Json工具类 - JsonUtils.java\JS...

    java字符串中${}或者{}等的占位符替换工具类

    Java字符串中${}或者{}等占位符替换工具类 Java字符串中${}或者{}等占位符替换工具类是一个功能强大且实用的工具类,它可以将Java字符串中的占位符依次替换为指定的值。该工具类的主要功能是实现占位符的替换,即将...

    Android开发常用工具类合集

    本资源包括常用工具类,目前收录了数组工具类、异步工具类、base64工具类、bitmap工具类、缓存工具类、时间工具类、http连接、json、IO、Map、MD5、数据库、SD卡、UbbToHtml等工具类合集

    java Base64工具类

    java Base64工具类 java Base64工具类java Base64工具类 java Base64工具类 java Base64工具类 java Base64工具类java Base64工具类 java Base64工具类 java Base64工具类 java Base64工具类java Base64工具类 java ...

    java连接SqlServer完整代码,工具类,jdbc

    java连接SqlServer完整代码,工具类,jdbc JDBC工具类的构建 1.资源释放 见https://mp.csdn.net/postedit/86577443 2.驱动防二次注册 ``` Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); //...

Global site tag (gtag.js) - Google Analytics