工具类

package com.mall.business.duizhang.creditcard;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.BreakIterator;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Random;
import java.util.ResourceBundle;
import java.util.Set;
import java.util.StringTokenizer;

import org.apache.log4j.Logger;

/**
*
*/

public class Util {
private Logger log=Logger.getLogger(Util.class);

private static final char[] QUOTE_ENCODE = """.toCharArray();
private static final char[] AMP_ENCODE = "&".toCharArray();
private static final char[] LT_ENCODE = "<".toCharArray();
private static final char[] GT_ENCODE = ">".toCharArray();
private static MessageDigest digest = null;

public Util() {
}
/*
  public static boolean validateUserName(String username) {
    Pattern p = Pattern.compile("^\\w+$");
    Matcher m = p.matcher(username);
    if (m.find()) {
      return true;
    }
    return false;
  }
*/
public static String Array2String(String[] values) {
String result = "";
if (values == null) {
return result;
}
int len = values.length;
for (int i = 0; i < len; i++) {
result += values[i] + ",";
}
if (result.endsWith(",")) {
result = result.substring(result.length() - 1);
}
return result;
}

public static String Array2String(Object[] values) {
String result = "";
if (values == null) {
return result;
}
int len = values.length;
for (int i = 0; i < len; i++) {
result += values[i].toString() + ",";
}
if (result.endsWith(",")) {
result = result.substring(result.length() - 1);
}
return result;
}

public static String Array2String(List values) {
String result = "";
if (values == null) {
return result;
}
int len = values.size();
for (int i = 0; i < len; i++) {
result += values.get(i).toString() + ",";
}
if (result.endsWith(",")) {
result = result.substring(result.length() - 1);
}
return result;
}
/*
* 转换数组为List
*/
public final static List arrayToList(String[] args) {
List list = new ArrayList();
if (args != null) {
if (args.length > 0) {
list = Arrays.asList(args);
}
}
return list;
}
public static String base64Encode(String txt) {
if (txt != null && txt.length() > 0) {
txt = new sun.misc.BASE64Encoder().encode(txt.getBytes());
}
return txt;
}

public static String base64Encode(byte[] txt) {
String encodeTxt = "";
if (txt != null && txt.length > 0) {
encodeTxt = new sun.misc.BASE64Encoder().encode(txt);
}
return encodeTxt;
}

public static String base64decode(String txt) {
if (txt != null && txt.length() > 0) {
byte[] buf;
try {
buf = new sun.misc.BASE64Decoder().decodeBuffer(txt);
txt = new String(buf);
} catch (IOException ex) {
}
}
return txt;
}

public static byte[] base64decodebyte(String txt) {
byte[] buf = null;
if (txt != null && txt.length() > 0) {
try {
buf = new sun.misc.BASE64Decoder().decodeBuffer(txt);
} catch (IOException ex) {
}
}
return buf;
}

/**
* Replaces all instances of oldString with newString in line.
*
* @param line the String to search to perform replacements on
* @param oldString the String that should be replaced by newString
* @param newString the String that will replace all instances of oldString
*
* @return a String will all instances of oldString replaced by newString
*/
public static final String replace(String line, String oldString, String newString) {
if (line == null) {
return null;
}
int i = 0;
if ((i = line.indexOf(oldString, i)) >= 0) {
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0) {
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}

/**
* Replaces all instances of oldString with newString in line with the
* added feature that matches of newString in oldString ignore case.
*
* @param line the String to search to perform replacements on
* @param oldString the String that should be replaced by newString
* @param newString the String that will replace all instances of oldString
*
* @return a String will all instances of oldString replaced by newString
*/
public static final String replaceIgnoreCase(String line, String oldString, String newString) {
if (line == null) {
return null;
}
String lcLine = line.toLowerCase();
String lcOldString = oldString.toLowerCase();
int i = 0;
if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
return buf.toString();
}
return line;
}

/**
* Replaces all instances of oldString with newString in line with the
* added feature that matches of newString in oldString ignore case.
* The count paramater is set to the number of replaces performed.
*
* @param line the String to search to perform replacements on
* @param oldString the String that should be replaced by newString
* @param newString the String that will replace all instances of oldString
* @param count a value that will be updated with the number of replaces
*      performed.
*
* @return a String will all instances of oldString replaced by newString
*/
public static final String replaceIgnoreCase(String line, String oldString, String newString, int[] count) {
if (line == null) {
return null;
}
String lcLine = line.toLowerCase();
String lcOldString = oldString.toLowerCase();
int i = 0;
if ((i = lcLine.indexOf(lcOldString, i)) >= 0) {
int counter = 0;
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = lcLine.indexOf(lcOldString, i)) > 0) {
counter++;
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
count[0] = counter;
return buf.toString();
}
return line;
}

/**
* Replaces all instances of oldString with newString in line.
* The count Integer is updated with number of replaces.
*
* @param line the String to search to perform replacements on
* @param oldString the String that should be replaced by newString
* @param newString the String that will replace all instances of oldString
*
* @return a String will all instances of oldString replaced by newString
*/
public static final String replace(String line, String oldString, String newString, int[] count) {
if (line == null) {
return null;
}
int i = 0;
if ((i = line.indexOf(oldString, i)) >= 0) {
int counter = 0;
counter++;
char[] line2 = line.toCharArray();
char[] newString2 = newString.toCharArray();
int oLength = oldString.length();
StringBuffer buf = new StringBuffer(line2.length);
buf.append(line2, 0, i).append(newString2);
i += oLength;
int j = i;
while ((i = line.indexOf(oldString, i)) > 0) {
counter++;
buf.append(line2, j, i - j).append(newString2);
i += oLength;
j = i;
}
buf.append(line2, j, line2.length - j);
count[0] = counter;
return buf.toString();
}
return line;
}

/**
* This method takes a string which may contain HTML tags (ie, &lt;b&gt;,
* &lt;table&gt;, etc) and converts the '&lt'' and '&gt;' characters to
* their HTML escape sequences.
*
* @param in the text to be converted.
* @return the input string with the characters '&lt;' and '&gt;' replaced
*  with their HTML escape sequences.
*/
public static final String escapeHTMLTags(String in) {
if (in == null) {
return null;
}
char ch;
int i = 0;
int last = 0;
char[] input = in.toCharArray();
int len = input.length;
StringBuffer out = new StringBuffer((int) (len * 1.3));
for (; i < len; i++) {
ch = input[i];
if (ch > '>') {
continue;
} else if (ch == '<') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(LT_ENCODE);
} else if (ch == '>') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(GT_ENCODE);
}
}
if (last == 0) {
return in;
}
if (i > last) {
out.append(input, last, i - last);
}
return out.toString();
}

/**
* Hashes a String using the Md5 algorithm and returns the result as a
* String of hexadecimal numbers. This method is synchronized to avoid
* excessive MessageDigest object creation. If calling this method becomes
* a bottleneck in your code, you may wish to maintain a pool of
* MessageDigest objects instead of using this method.
* <p>
* A hash is a one-way function -- that is, given an
* input, an output is easily computed. However, given the output, the
* input is almost impossible to compute. This is useful for passwords
* since we can store the hash and a hacker will then have a very hard time
* determining the original password.
* <p>
* In Jive, every time a user logs in, we simply
* take their plain text password, compute the hash, and compare the
* generated hash to the stored hash. Since it is almost impossible that
* two passwords will generate the same hash, we know if the user gave us
* the correct password or not. The only negative to this system is that
* password recovery is basically impossible. Therefore, a reset password
* method is used instead.
*
* @param data the String to compute the hash of.
* @return a hashed version of the passed-in String
*/
public synchronized static final String hash(String data) {
if (digest == null) {
try {
digest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException nsae) {
System.err.println("Failed to load the MD5 MessageDigest. " + "We will be unable to function normally.");
nsae.printStackTrace();
}
}
// Now, compute hash.
digest.update(data.getBytes());
return encodeHex(digest.digest());
}

/**
* Turns an array of bytes into a String representing each byte as an
* unsigned hex number.
* <p>
* Method by Santeri Paavolainen, Helsinki Finland 1996<br>
* (c) Santeri Paavolainen, Helsinki Finland 1996<br>
* Distributed under LGPL.
*
* @param bytes an array of bytes to convert to a hex-string
* @return generated hex string
*/
public static final String encodeHex(byte[] bytes) {
StringBuffer buf = new StringBuffer(bytes.length * 2);
int i;

for (i = 0; i < bytes.length; i++) {
if (((int) bytes[i] & 0xff) < 0x10) {
buf.append("0");
}
buf.append(Long.toString((int) bytes[i] & 0xff, 16));
}
return buf.toString().toUpperCase();
}

/**
* Turns a hex encoded string into a byte array. It is specifically meant
* to "reverse" the toHex(byte[]) method.
*
* @param hex a hex encoded String to transform into a byte array.
* @return a byte array representing the hex String[
*/
public static final byte[] decodeHex(String hex) {
char[] chars = hex.toCharArray();
byte[] bytes = new byte[chars.length / 2];
int byteCount = 0;
for (int i = 0; i < chars.length; i += 2) {
byte newByte = 0x00;
newByte |= hexCharToByte(chars[i]);
newByte <<= 4;
newByte |= hexCharToByte(chars[i + 1]);
bytes[byteCount] = newByte;
byteCount++;
}
return bytes;
}

/**
* Returns the the byte value of a hexadecmical char (0-f). It's assumed
* that the hexidecimal chars are lower case as appropriate.
*
* @param ch a hexedicmal character (0-f)
* @return the byte value of the character (0x00-0x0F)
*/
private static final byte hexCharToByte(char ch) {
switch (ch) {
case '0' :
return 0x00;
case '1' :
return 0x01;
case '2' :
return 0x02;
case '3' :
return 0x03;
case '4' :
return 0x04;
case '5' :
return 0x05;
case '6' :
return 0x06;
case '7' :
return 0x07;
case '8' :
return 0x08;
case '9' :
return 0x09;
case 'a' :
return 0x0A;
case 'b' :
return 0x0B;
case 'c' :
return 0x0C;
case 'd' :
return 0x0D;
case 'e' :
return 0x0E;
case 'f' :
return 0x0F;
}
return 0x00;
}

/**
* Converts a line of text into an array of lower case words using a
* BreakIterator.wordInstance(). <p>
*
* This method is under the Jive Open Source Software License and was
* written by Mark Imbriaco.
*
* @param text a String of text to convert into an array of words
* @return text broken up into an array of words.
*/
public static final String[] toLowerCaseWordArray(String text) {
if (text == null || text.length() == 0) {
return new String[0];
}

ArrayList wordList = new ArrayList();
BreakIterator boundary = BreakIterator.getWordInstance();
boundary.setText(text);
int start = 0;

for (int end = boundary.next(); end != BreakIterator.DONE; start = end, end = boundary.next()) {
String tmp = text.substring(start, end).trim();
// Remove characters that are not needed.
tmp = replace(tmp, "+", "");
tmp = replace(tmp, "/", "");
tmp = replace(tmp, "\\", "");
tmp = replace(tmp, "#", "");
tmp = replace(tmp, "*", "");
tmp = replace(tmp, ")", "");
tmp = replace(tmp, "(", "");
tmp = replace(tmp, "&", "");
if (tmp.length() > 0) {
wordList.add(tmp);
}
}
return (String[]) wordList.toArray(new String[wordList.size()]);
}

/**
* Pseudo-random number generator object for use with randomString().
* The Random class is not considered to be cryptographically secure, so
* only use these random Strings for low to medium security applications.
*/
private static Random randGen = new Random();

/**
* Array of numbers and letters of mixed case. Numbers appear in the list
* twice so that there is a more equal chance that a number will be picked.
* We can use the array to get a random number or letter by picking a random
* array index.
*/
private static char[] numbersAndLetters = ("0123456789abcdefghijklmnopqrstuvwxyz" + "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ").toCharArray();

/**
* Returns a random String of numbers and letters (lower and upper case)
* of the specified length. The method uses the Random class that is
* built-in to Java which is suitable for low to medium grade security uses.
* This means that the output is only pseudo random, i.e., each number is
* mathematically generated so is not truly random.<p>
*
* The specified length must be at least one. If not, the method will return
* null.
*
* @param length the desired length of the random String to return.
* @return a random String of numbers and letters of the specified length.
*/
public static final String randomString(int length) {
if (length < 1) {
return null;
}
// Create a char buffer to put random letters and numbers in.
char[] randBuffer = new char[length];
for (int i = 0; i < randBuffer.length; i++) {
randBuffer[i] = numbersAndLetters[randGen.nextInt(71)];
}
return new String(randBuffer);
}

/**
* Intelligently chops a String at a word boundary (whitespace) that occurs
* at the specified index in the argument or before. However, if there is a
* newline character before <code>length</code>, the String will be chopped
* there. If no newline or whitespace is found in <code>string</code> up to
* the index <code>length</code>, the String will chopped at <code>length</code>.
* <p>
* For example, chopAtWord("This is a nice String", 10) will return
* "This is a" which is the first word boundary less than or equal to 10
* characters into the original String.
*
* @param string the String to chop.
* @param length the index in <code>string</code> to start looking for a
*       whitespace boundary at.
* @return a substring of <code>string</code> whose length is less than or
*       equal to <code>length</code>, and that is chopped at whitespace.
*/
public static final String chopAtWord(String string, int length) {
if (string == null) {
return string;
}

char[] charArray = string.toCharArray();
int sLength = string.length();
if (length < sLength) {
sLength = length;
}

// First check if there is a newline character before length; if so,
// chop word there.
for (int i = 0; i < sLength - 1; i++) {
// Windows
if (charArray[i] == '\r' && charArray[i + 1] == '\n') {
return string.substring(0, i + 1);
}
// Unix
else if (charArray[i] == '\n') {
return string.substring(0, i);
}
}
// Also check boundary case of Unix newline
if (charArray[sLength - 1] == '\n') {
return string.substring(0, sLength - 1);
}

// Done checking for newline, now see if the total string is less than
// the specified chop point.
if (string.length() < length) {
return string;
}

// No newline, so chop at the first whitespace.
for (int i = length - 1; i > 0; i--) {
if (charArray[i] == ' ') {
return string.substring(0, i).trim();
}
}

// Did not find word boundary so return original String chopped at
// specified length.
return string.substring(0, length);
}

/**
* Escapes all necessary characters in the String so that it can be used
* in an XML doc.
*
* @param string the string to escape.
* @return the string with appropriate characters escaped.
*/
public static final String escapeForXML(String string) {
if (string == null) {
return null;
}
char ch;
int i = 0;
int last = 0;
char[] input = string.toCharArray();
int len = input.length;
StringBuffer out = new StringBuffer((int) (len * 1.3));
for (; i < len; i++) {
ch = input[i];
if (ch > '>') {
continue;
} else if (ch == '<') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(LT_ENCODE);
} else if (ch == '&') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(AMP_ENCODE);
} else if (ch == '"') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(QUOTE_ENCODE);
}
}
if (last == 0) {
return string;
}
if (i > last) {
out.append(input, last, i - last);
}
return out.toString();
}

public static final String escapeForSpecial(String string) {
if (string == null) {
return null;
}
char ch;
int i = 0;
int last = 0;
char[] input = string.toCharArray();
int len = input.length;
StringBuffer out = new StringBuffer((int) (len * 1.3));
for (; i < len; i++) {
ch = input[i];
if (ch > '>') {
continue;
} else if (ch == '<') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(LT_ENCODE);
} else if (ch == '&') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(AMP_ENCODE);
} else if (ch == '"') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(QUOTE_ENCODE);
} else if (ch == '>') {
if (i > last) {
out.append(input, last, i - last);
}
last = i + 1;
out.append(GT_ENCODE);
}
}
if (last == 0) {
return string;
}
if (i > last) {
out.append(input, last, i - last);
}
return out.toString();
}

/**
* Unescapes the String by converting XML escape sequences back into normal
* characters.
*
* @param string the string to unescape.
* @return the string with appropriate characters unescaped.
*/
public static final String unescapeFromXML(String string) {
string = replace(string, "&lt;", "<");
string = replace(string, "&gt;", ">");
string = replace(string, "&quot;", "\"");
return replace(string, "&amp;", "&");
}

private static final char[] zeroArray = "0000000000000000".toCharArray();

/**
* Pads the supplied String with 0's to the specified length and returns
* the result as a new String. For example, if the initial String is
* "9999" and the desired length is 8, the result would be "00009999".
* This type of padding is useful for creating numerical values that need
* to be stored and sorted as character data. Note: the current
* implementation of this method allows for a maximum <tt>length</tt> of
* 16.
*
* @param string the original String to pad.
* @param length the desired length of the new padded String.
* @return a new String padded with the required number of 0's.
*/
public static final String zeroPadString(String string, int length) {
if (string == null || string.length() > length) {
return string;
}
StringBuffer buf = new StringBuffer(length);
buf.append(zeroArray, 0, length - string.length()).append(string);
return buf.toString();
}

/**
* Formats a Date as a fifteen character long String made up of the Date's
* padded millisecond value.
*
* @return a Date encoded as a String.
*/
public static final String dateToMillis(Date date) {
return zeroPadString(Long.toString(date.getTime()), 15);
}

/**
* Formats a Date as a fifteen character long String made up of the Date's
* padded millisecond value.
*
* @return a Date encoded as a String.
*/
public static final String collectionToString(Collection c, String spilt) {
if (c == null) {
return null;
}
if (spilt == null) {
return null;
}
String ret = "";
List a = new ArrayList(c);
try {
for (int i = 0; i < a.size(); i++) {
String t = (String) a.get(i);
if (i == a.size() - 1) {
ret = ret + t;
} else {
ret = ret + t + spilt;
}
}
return ret;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}

public static String genPassword(int length) {
if (length < 1) {
return null;
}
String[] strChars =
{
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"a",
"b",
"c",
"d",
"e",
"f",
"g",
"h",
"i",
"j",
"k",
"m",
"n",
"p",
"q",
"r",
"s",
"t",
"u",
"v",
"w",
"x",
"y",
"z",
"a" };
//没有0,o,l和I,以免误解
StringBuffer strPassword = new StringBuffer();
int nRand = (int) java.lang.Math.round(java.lang.Math.random() * 100);
for (int i = 0; i < length; i++) {
nRand = (int) java.lang.Math.round(java.lang.Math.random() * 100);
strPassword.append(strChars[nRand % (strChars.length - 1)]);
//strPassword += strChars[nRand % (strChars.length - 1)];
}
return strPassword.toString();
}

public static String genNumPassword(int length) {
if (length < 1) {
return null;
}
String[] strChars = { "1", "2", "3", "4", "5", "6", "7", "8", "9" };

StringBuffer strPassword = new StringBuffer();
int nRand = (int) java.lang.Math.round(java.lang.Math.random() * 100);
for (int i = 0; i < length; i++) {
nRand = (int) java.lang.Math.round(java.lang.Math.random() * 100);
strPassword.append(strChars[nRand % (strChars.length - 1)]);
//strPassword += strChars[nRand % (strChars.length - 1)];
}
return strPassword.toString();
}

public static String genEmptyString(int length) {
if (length < 1) {
return null;
}
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
sb.append(" ");
}
return sb.toString();
}

public static String getHTML(String str) {
String strret = null;
URL rTmp = null;
InputStream ins = null;
BufferedReader breader = null;
InputStreamReader isreader = null;
try {
rTmp = new URL(str);
ins = rTmp.openStream();
isreader = new InputStreamReader(ins);
breader = new BufferedReader(isreader);
String info = breader.readLine();
strret = info;
info = breader.readLine();
while (info != null) {
strret = strret + "\n" + info;
info = breader.readLine();
}
} catch (Exception e) {
//e.printStackTrace(System.err);
//return null;
} finally {
try {
if (breader != null) {
breader.close();
}
} catch (IOException ex) {
}

try {
if (isreader != null) {
isreader.close();
}
} catch (IOException ex1) {
}

try {
if (ins != null) {
ins.close();
}
} catch (IOException ex2) {
}

return strret;
}
}

public static String getAsciiString(int digit) {
byte ret[] = new byte[1];
ret[0] = (byte) digit;
return new String(ret);
}

public static int getAsciiNum(String s) {
if (s.length() < 1) {
return 0;
}
byte b = s.getBytes()[0];
return b;
}
public static String getCurrDate() {
Date date = new Date();
return Util.formatDate4(date);
}

public static String getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
String s = outFormat.format(now);
return s;
}

public static String getCurrTime2() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("HHmmss");
String s = outFormat.format(now);
return s;
}

/**
* Formats a Date object to return a date using the global locale.
*/
public static String formatDate(Date date) {
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd");
return outFormat.format(date);
}

/**
* Formats a Date object to return a date and time using the global locale.
*/
public static String formatDateTime(Date date) {
SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return outFormat.format(date);
}

public static String formatDate2(Date myDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd");
String strDate = formatter.format(myDate);
return strDate;
}

public static String formatDate3(Date myDate) {
SimpleDateFormat formatter = new SimpleDateFormat("MM-dd HH:mm");
String strDate = formatter.format(myDate);
return strDate;
}

public static String formatDate4(Date myDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String strDate = formatter.format(myDate);
return strDate;
}

public static String formatDate5(Date myDate) {
String strDate = getYear(myDate) + "-" + getMonth(myDate) + "-" + getDay(myDate);
return strDate;
}

public static String formatDate6(Date myDate) {
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm");
String strDate = formatter.format(myDate);
return strDate;
}

public static Date stringToDate(String str, String format) {

if (str == null || format == null) {
return null;
}
DateFormat sdf = new SimpleDateFormat(format);

java.util.Date date = null;
try {
date = sdf.parse(str);
} catch (Exception e) {
e.printStackTrace();
}
return date;
}

public static long Date2Long(int year, int month, int date) {
Calendar cld = Calendar.getInstance();
month = month - 1;
cld.set(year, month, date);
return cld.getTime().getTime();
}

public static long Time2Long(int year, int month, int date, int hour, int minute, int second) {
Calendar cld = Calendar.getInstance();
month = month - 1;
cld.set(year, month, date, hour, minute, second);
return cld.getTime().getTime();
}

public static int getYear(long t) {
Calendar cld = Calendar.getInstance();
if (t > 0) {
cld.setTime(new java.util.Date(t));
}
return cld.get(Calendar.YEAR);
}

public static int getMonth(long t) {
Calendar cld = Calendar.getInstance();
if (t > 0) {
cld.setTime(new java.util.Date(t));
}
return cld.get(Calendar.MONTH) + 1;
}

public static int getDay(long t) {
Calendar cld = Calendar.getInstance();
if (t > 0) {
cld.setTime(new java.util.Date(t));
}
return cld.get(Calendar.DAY_OF_MONTH);
}

public static int getHour(long t) {
Calendar cld = Calendar.getInstance();
if (t > 0) {
cld.setTime(new java.util.Date(t));
}
return cld.get(Calendar.HOUR_OF_DAY);
}

public static int getMinute(long t) {
Calendar cld = Calendar.getInstance();
if (t > 0) {
cld.setTime(new java.util.Date(t));
}
return cld.get(Calendar.MINUTE);
}

public static int getSecond(long t) {
Calendar cld = Calendar.getInstance();
if (t > 0) {
cld.setTime(new java.util.Date(t));
}
return cld.get(Calendar.SECOND);
}

public static int getYear(Date date) {
Calendar cld = Calendar.getInstance();
cld.setTime(date);
return cld.get(Calendar.YEAR);
}

public static int getMonth(Date date) {
Calendar cld = Calendar.getInstance();
cld.setTime(date);
return cld.get(Calendar.MONTH) + 1;
}

public static int getDay(Date date) {
Calendar cld = Calendar.getInstance();
cld.setTime(date);
return cld.get(Calendar.DAY_OF_MONTH);
}

public static int getHour(Date date) {
Calendar cld = Calendar.getInstance();
cld.setTime(date);
return cld.get(Calendar.HOUR_OF_DAY);
}

public static int getMinute(Date date) {
Calendar cld = Calendar.getInstance();
cld.setTime(date);
return cld.get(Calendar.MINUTE);
}

public static int getSecond(Date date) {
Calendar cld = Calendar.getInstance();
cld.setTime(date);
return cld.get(Calendar.SECOND);
}

public static int getYear() {
Calendar cld = Calendar.getInstance();
cld.setTime(new java.util.Date());
return cld.get(Calendar.YEAR);
}

public static int getMonth() {
Calendar cld = Calendar.getInstance();
cld.setTime(new java.util.Date());
return cld.get(Calendar.MONTH) + 1;
}

public static int getDay() {
Calendar cld = Calendar.getInstance();
cld.setTime(new java.util.Date());
return cld.get(Calendar.DAY_OF_MONTH);
}
/*
  public static String replaceComma(String text) {
    if (text != null) {
      text = text.replaceAll(",", ",");
    }
    return text;
  }

  public static String replaceBr(String text) {
    if (text != null) {
      text = text.replaceAll("\n", "<BR>");
    }
    return text;
  }
*/
public static long getLongTime() {
return System.currentTimeMillis();
}
/**
* 判断字符串是否为空串(null或者内容为空)
  * @param str
* @return
*/
public static boolean isEmpty(String str) {
if ((null == str) || (str.trim().length() <= 0)) {
return true;
}

return false;
}

/**
* 判断集合是否为空(null或者内容为空)
* @param map Map
* @return boolean
*/
public static boolean isEmpty(Set set) {
if ((null == set) || (set.size() <= 0)) {
return true;
}

return false;
}

/**
* 清除字符串的左右空格
* @param str
* @return:返回清除左右空格后的字符串
*/
public static String trim(String str) {
if (null == str) {
return "";
}

return str.trim();
}

public static void main(String[] args) {
String t = "abcdfg\"sfdfaeeed<a href=>ghjfghj";
t = escapeForSpecial(t);

}

public static Calendar getCalendarByString(String str, String format) {
if (str == null || "".equals(str)) {
return null;
}
//format eg: yyyy-MM-dd HH:mm:ss
SimpleDateFormat standartDateTimeFormat = new SimpleDateFormat(format);
Date date = null;
try {
date = standartDateTimeFormat.parse(str);

} catch (ParseException e) {
e.printStackTrace();
return null;
}
Calendar c = Calendar.getInstance();
c.setTime(date);
return c;
}

public static Calendar getCalendarByString(String str) {
if (str == null || "".equals(str)) {
return null;
}
SimpleDateFormat standartDateTimeFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date date = null;
try {
date = standartDateTimeFormat.parse(str);

} catch (ParseException e) {
e.printStackTrace();
return null;
}
Calendar c = Calendar.getInstance();

c.setTime(date);
return c;
}

public static String getDateStringByCalendar(Calendar c) {
if (c == null)
return "";
return c.get(Calendar.YEAR) + "-" + (c.get(Calendar.MONTH) + 1) + "-" + c.get(Calendar.DATE);
}

public static String getDDMMYYToYYMMDD(String strtm) {
String start_time = "";
String start_date = "";
String str_year = "";
String str_date = "";
String str_month = "";
int k = 0;
StringTokenizer st1 = new StringTokenizer(strtm);

while (st1.hasMoreTokens()) {
if (k == 0)
start_date = (String) st1.nextToken();
if (k == 1)
start_time = (String) st1.nextToken();
k++;
}
StringTokenizer st2 = new StringTokenizer(start_date + "-", "-");
str_date = st2.nextToken();
str_month = st2.nextToken();
str_year = st2.nextToken();
return (str_year + "-" + str_month + "-" + str_date + " " + start_time).trim();
}

public static String getFormatYYMMDDHHMMSS(String strtm) {
String start_time = "";
String start_date = "";
String str_year = "";
String str_date = "";
String str_month = "";
String str_hour = "";
String str_minute = "";
String str_second = "";

int k = 0;
if (strtm.trim().equals(""))
return strtm.trim();
StringTokenizer st1 = new StringTokenizer(strtm);

while (st1.hasMoreTokens()) {
if (k == 0)
start_date = (String) st1.nextToken();
if (k == 1)
start_time = (String) st1.nextToken();
k++;
}

StringTokenizer st2 = new StringTokenizer(start_date + "-", "-");
str_year = st2.nextToken();
str_month = st2.nextToken();
if (str_month.length() == 1)
str_month = "0" + str_month;

str_date = st2.nextToken();
if (str_date.length() == 1)
str_date = "0" + str_date;
if (!start_time.trim().equals("")) {
st2 = new StringTokenizer(start_time + ":", ":");

str_hour = st2.nextToken();
if (str_hour.length() == 1)
str_hour = "0" + str_hour;
str_minute = st2.nextToken();
if (str_minute.length() == 1)
str_minute = "0" + str_minute;
str_second = st2.nextToken();
if (str_second.length() == 1)
str_second = "0" + str_second;
start_time = (str_hour + ":" + str_minute + ":" + str_second).substring(0, ;
}
return (str_year + "-" + str_month + "-" + str_date + " " + start_time).trim();
}

public static String getFormatYYMMDDHHMM(String strtm) {
String start_time = "";
String start_date = "";
String str_year = "";
String str_date = "";
String str_month = "";
String str_hour = "";
String str_minute = "";
String str_second = "";

int k = 0;
if (strtm.trim().equals(""))
return strtm.trim();
StringTokenizer st1 = new StringTokenizer(strtm);

while (st1.hasMoreTokens()) {
if (k == 0)
start_date = (String) st1.nextToken();
if (k == 1)
start_time = (String) st1.nextToken();
k++;
}

StringTokenizer st2 = new StringTokenizer(start_date + "-", "-");
str_year = st2.nextToken();
str_month = st2.nextToken();
if (str_month.length() == 1)
str_month = "0" + str_month;

str_date = st2.nextToken();
if (str_date.length() == 1)
str_date = "0" + str_date;
if (!start_time.trim().equals("")) {
st2 = new StringTokenizer(start_time + ":", ":");

str_hour = st2.nextToken();
if (str_hour.length() == 1)
str_hour = "0" + str_hour;
str_minute = st2.nextToken();
if (str_minute.length() == 1)
str_minute = "0" + str_minute;
str_second = st2.nextToken();
if (str_second.length() == 1)
str_second = "0" + str_second;

start_time = (str_hour + ":" + str_minute + ":" + str_second).substring(0, 5);

}
return (str_year + "-" + str_month + "-" + str_date + " " + start_time).trim();
}

public static String chkNull(Object obj) {
if (obj == null) {
return "";
}
if (((String) obj).equalsIgnoreCase("null")) {
return "";
}
return (String) obj;
}
public static String chkNullTrim(Object obj) {
if (obj == null) {
return "";
}
if (((String) obj).equalsIgnoreCase("null")) {
return "";
}
return Util.replace(((String) obj).trim()," ","");
}
public static String chkNullSpaceOne(Object obj) {
if (obj == null) {
return " ";
}
if (((String) obj).equalsIgnoreCase("null")) {
return " ";
}
return ((String) obj).trim();
}
public static String chkNullCharacterTrim(Object obj) {
if (obj == null) {
return "";
}
if ((obj.toString()).equalsIgnoreCase("null")) {
return "";
}
return ((String) obj.toString()).trim();
}

public static String chkBigDecimalNull(Object obj) {

if (obj == null) {
return "0";
}

String bd = ((BigDecimal) obj).toString();

if (bd.equalsIgnoreCase("null")) {
return "0";
}

return bd;
}
public static BigDecimal chkBigDecimalNullBigD(Object obj) {

if (obj == null) {
return new BigDecimal("0");
}

String bd = ((BigDecimal) obj).toString();

if (bd.equalsIgnoreCase("null")) {
return new BigDecimal("0");
}

return (BigDecimal) obj;
}
public static String chkIntegerNull(Object obj) {

if (obj == null) {
return "0";
}

String bd = ((Integer) obj).toString();

if (bd.equalsIgnoreCase("null")) {
return "0";
}

return bd;
}
public static Integer chkIntegerNullInt(Object obj) {

if (obj == null) {
return new Integer("0");
}

String bd = ((Integer) obj).toString();

if (bd.equalsIgnoreCase("null")) {
return new Integer("0");
}

return (Integer) obj;
}
public static Short chkShortNullSht(Object obj) {

if (obj == null) {
return new Short("0");
}

String bd = ((Short) obj).toString();

if (bd.equalsIgnoreCase("null")) {
return new Short("0");
}

return (Short) obj;
}
public static String getHTMLComboString(HashMap typeList, ArrayList typeKeys, String nowValue) {
String rtStr = "";
StringBuffer strBuf = new StringBuffer();
strBuf.append("<option></option>");

for (int i = 0; i < typeKeys.size(); i++) {
String org_no = (String) typeKeys.get(i);
strBuf.append("<OPTION value='" + org_no + "' ");
if (org_no.equals(nowValue))
strBuf.append("selected");
strBuf.append(" >");
strBuf.append(typeList.get(org_no));
strBuf.append(" </OPTION> ");
}
rtStr = strBuf.toString();
return rtStr;
}

public static String getHTMLComboString2(HashMap typeList, ArrayList typeKeys, String nowValue) {
String rtStr = "";
StringBuffer strBuf = new StringBuffer();

for (int i = 0; i < typeKeys.size(); i++) {
String org_no = (String) typeKeys.get(i);
strBuf.append("<OPTION value='" + org_no + "' ");
if (org_no.equals(nowValue))
strBuf.append("selected");
strBuf.append(" >");
strBuf.append(typeList.get(org_no));
strBuf.append(" </OPTION> ");
}
rtStr = strBuf.toString();
return rtStr;
}

/**
   * 将字符串按指定的符号分割成数组(数组内容不包括指定符号)
   * @param value
   * @param split
   * @return
   */
public static String[] splitString(String value, String split) {
value = Util.trim(value);
if (Util.isEmpty(value) || Util.isEmpty(split)) {
return null;
}

Collection coll = new ArrayList();
int StartIndex = 0;
int EndIndex = value.indexOf(split, StartIndex);
while (EndIndex >= 0) {
coll.add(value.substring(StartIndex, EndIndex));
StartIndex = EndIndex + split.length();
EndIndex = value.indexOf(split, StartIndex);
}
coll.add(value.substring(StartIndex, value.length())); // 剩余字符
// 转成字符串数组
int i = 0;
String vals[] = new String[coll.size()];
for (Iterator iter = coll.iterator(); iter.hasNext();) {
vals[i++] = Util.trim((String) (iter.next()));
}

return vals;
}
/**
* 字符串填充函数
*
* @param string
* @param filler
* @param totalLength
* @param atEnd
* @return 字符填充后的string
*/
public static String fillString(String string, char filler,int totalLength,boolean atEnd) {

byte[] tempbyte = (string==null?"":string).getBytes();

int currentLength = tempbyte.length;

int delta = totalLength - currentLength;

for (int i = 0; i < delta; i++) {

if (atEnd) {

string += filler;

}

else {

string = filler + string;

}

}

return string;

}


/**
*  把 数组1 与数组2 相加。
* @param src 开始数组,
* @param dst 结束数组
* @return 返回 开始数组+结束数据
*/
public static byte[] appendArray(byte[] src, byte[] dst)
{
byte[] newBytes = new byte[src.length + dst.length];
System.arraycopy(src, 0, newBytes, 0, src.length);
System.arraycopy(dst, 0, newBytes, src.length, dst.length);
return newBytes;
}

/**
* 构造实例方法名
* @param str 字符串
* @return set方法名
*/
public static String methodName(String str)
{
String prefix = str.substring(0, 1).toUpperCase();
String postfix = str.substring(1);
return "set" + prefix + postfix;
}

/**
*
*
* @param Number
* @param decimal
* @return
*/
public static String ParseDecNumner(String Number, int decimal) {
String value = null;
int divid = 1;
if (decimal > 0) {
for (int i = 0; i < decimal; i++) {
divid = divid * 10;
}
value = String.valueOf(Float.parseFloat(Number) / (divid * 1.0));
int pos = value.indexOf(".") + 1;
pos = value.length() - pos;
if (pos < decimal) {
for (int i = pos; i < decimal; i++) {
value = value + "0";
}
} else if (pos > decimal) {
value = value.substring(0, value.length() - pos + decimal);
}
} else {
value = Number;
}
return value;
}
/**
* 金额转换,flag如果是0,元转为分;flag如果是1,分转为元;
*
* @param flag,txnAt
* @return
*/
public static String transTxnAt(int flag, String txnAt) {

if (txnAt == null || txnAt.equals(""))
return txnAt;

BigDecimal tmpTxnAt = new BigDecimal(txnAt);
// long longTxnAt = Long.parseLong(String.valueOf(tmpTxnAt));
String objTxnAt = null;
if (flag == 0) {

tmpTxnAt = tmpTxnAt.multiply(new BigDecimal(100));

objTxnAt = String.valueOf(tmpTxnAt.longValue());
} else
objTxnAt = ParseDecNumner(txnAt, 2);
return objTxnAt;

}

/**
* 格式化金额
* @param str 字符串
* @param len 长度
* @return
*/
public static String formatNumber(Object str,int len) {

if (str == null || str == "") {
return "0";
}
String number = toString(new BigDecimal((String)str),len);
return replace(number,".","");
}

/**
* 对数字进行格式化输出
* @param bd
* @param scale:小数点后的位数
* @return:格式化后的数字
*/
public static String toString(BigDecimal bd, int scale) {
if (null == bd) {
bd = new BigDecimal(0);
}
bd = bd.setScale(scale, BigDecimal.ROUND_HALF_EVEN);
return bd.toString();
}

/**
  * 补空字符串
  * @param str 字符串
  * @param length 长度
  * @return 返回补空字符串
  */
public static String fillStrToLen(String str, int length)
{
if (str == null)
str = "";
int i = 0;
try
{
i = str.getBytes("GBK").length;
}
catch (UnsupportedEncodingException e)
{
}
if (length < i)
{
throw new StringIndexOutOfBoundsException(length);
}
int j = length - i;
for (int k = 0; k < j; k++)
{
str = str + " ";
}
return str;
}

/**
* 字符串前补0
* @param str 字符串
* @param length 长度
* @return 返回补0字符串
*/
   public static String fillZeroToLen(String str, int length)
   {
   if (str == null)
   str = "";
   int i = 0;
   try
   {
   i = str.getBytes("GBK").length;
   }
   catch (UnsupportedEncodingException e)
   {
   }
   if (length < i)
   {
   throw new StringIndexOutOfBoundsException(length);
   }
   int j = length - i;
   for (int k = 0; k < j; k++)
   {
   str = "0" + str;
   }
   return str;
   }
  
private static final String BUNDLE_NAME = "config";
private static final ResourceBundle RESOURCE_BUNDLE =
ResourceBundle.getBundle(BUNDLE_NAME, Locale.getDefault());

public static String getSysParam(String key){
try {
return RESOURCE_BUNDLE.getString(key);
} catch (MissingResourceException e) {
System.out.println("获取系统参数异常"+e);
return null;
}
}

/**
  增加判断ASCII的
  **/
public static boolean isXMLCharacter(int c) {
if (c <= 0xD7FF) {
if (c >= 0x20)
return true;
else {
if (c == '\n')
return true;
if (c == '\r')
return true;
if (c == '\t')
return true;
return false;
}
}

if (c < 0xE000)
return false;
if (c <= 0xFFFD)
return true;
if (c < 0x10000)
return false;
if (c <= 0x10FFFF)
return true;

return false;
}

public static String repacleCharacterData(String text) {

String value = text;

if (text == null) {
return "";
}

char[] data = text.toCharArray();
for (int i = 0; i < data.length; i++) {
char c = data[i];
int result = c;

if (result >= 0xD800 && result <= 0xDBFF) {

int high = c;
try {
int low = text.charAt(i + 1);
if (low < 0xDC00 || low > 0xDFFF) {
value = String.valueOf(data[i]);
text = replace(text, value, "");
return text;
}
result = (high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000;
i++;
} catch (IndexOutOfBoundsException e) {
value = String.valueOf(data[i]);
text = replace(text, value, "");
return text;
}
}
if (!isXMLCharacter(result)) {

value = String.valueOf(data[i]);
text = replace(text, value, "");
return text;
}
}

return text;
}


}

猜你喜欢

转载自tangkuo.iteye.com/blog/2256000