注册 登录  
 加关注
   显示下一条  |  关闭
温馨提示!由于新浪微博认证机制调整,您的新浪微博帐号绑定已过期,请重新绑定!立即重新绑定新浪微博》  |  关闭

放飞自由

年轻人,如果三年的时间里,没有任何想法,他这一生,就基本这个样子,没有多大改变。

 
 
 

日志

 
 

StringUtil常用字符串(一)  

2013-06-10 23:34:10|  分类: JAVA后台 |  标签: |举报 |字号 订阅

  下载LOFTER 我的照片书  |

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.StringReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.MessageDigest;

import java.text.MessageFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Properties;
import java.util.Random;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.ServletContext;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

import org.apache.log4j.Logger;

/**
* 字符串操作工具类
*/
@SuppressWarnings("unchecked")
public class StringUtils {

private static final Logger log = Logger.getLogger(StringUtils.class);

private static final String FOLDER_SEPARATOR = "/";

private static final String WINDOWS_FOLDER_SEPARATOR = "\\";

private static final String TOP_PATH = "..";

private static final String CURRENT_PATH = ".";

private static final char EXTENSION_SEPARATOR = '.';

/**
* Check if a String has length.
* <p>
*
* <pre>
* StringUtils.hasLength(null) = false
* StringUtils.hasLength(&quot;&quot;) = false
* StringUtils.hasLength(&quot; &quot;) = true
* StringUtils.hasLength(&quot;Hello&quot;) = true
* </pre>
*
* @param str
* the String to check, may be <code>null</code>
* @return <code>true</code> if the String is not null and has length
*/
public static boolean hasLength(String str) {
return (str != null && str.length() > 0);
}

/**
* Check if a String has text. More specifically, returns <code>true</code>
* if the string not <code>null<code>, it's <code>length is > 0</code>, and it has at least one
* non-whitespace character.
* <p>
*
* <pre>
* StringUtils.hasText(null) = false
* StringUtils.hasText(&quot;&quot;) = false
* StringUtils.hasText(&quot; &quot;) = false
* StringUtils.hasText(&quot;12345&quot;) = true
* StringUtils.hasText(&quot; 12345 &quot;) = true
* </pre>
*
* @param str
* the String to check, may be <code>null</code>
* @return <code>true</code> if the String is not null, length > 0, and not
* whitespace only
* @see java.lang.Character#isWhitespace
*/
public static boolean hasText(String str) {
int strLen;
if (str == null || (strLen = str.length()) == 0) {
return false;
}
for (int i = 0; i < strLen; i++) {
if (!Character.isWhitespace(str.charAt(i))) {
return true;
}
}
return false;
}

/**
* Trim leading and trailing whitespace from the given String.
*
* @param str
* the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuffer buf = new StringBuffer(str);
while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {
buf.deleteCharAt(0);
}
while (buf.length() > 0
&& Character.isWhitespace(buf.charAt(buf.length() - 1))) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}

/**
* Trim leading whitespace from the given String.
*
* @param str
* the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimLeadingWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuffer buf = new StringBuffer(str);
while (buf.length() > 0 && Character.isWhitespace(buf.charAt(0))) {
buf.deleteCharAt(0);
}
return buf.toString();
}

/**
* Trim trailing whitespace from the given String.
*
* @param str
* the String to check
* @return the trimmed String
* @see java.lang.Character#isWhitespace
*/
public static String trimTrailingWhitespace(String str) {
if (!hasLength(str)) {
return str;
}
StringBuffer buf = new StringBuffer(str);
while (buf.length() > 0
&& Character.isWhitespace(buf.charAt(buf.length() - 1))) {
buf.deleteCharAt(buf.length() - 1);
}
return buf.toString();
}

/**
* Test if the given String starts with the specified prefix, ignoring
* upper/lower case.
*
* @param str
* the String to check
* @param prefix
* the prefix to look for
* @see java.lang.String#startsWith
*/
public static boolean startsWithIgnoreCase(String str, String prefix) {
if (str == null || prefix == null) {
return false;
}
if (str.startsWith(prefix)) {
return true;
}
if (str.length() < prefix.length()) {
return false;
}
String lcStr = str.substring(0, prefix.length()).toLowerCase();
String lcPrefix = prefix.toLowerCase();
return lcStr.equals(lcPrefix);
}

/**
* Test if the given String ends with the specified suffix, ignoring
* upper/lower case.
*
* @param str
* the String to check
* @param suffix
* the suffix to look for
* @see java.lang.String#endsWith
*/
public static boolean endsWithIgnoreCase(String str, String suffix) {
if (str == null || suffix == null) {
return false;
}
if (str.endsWith(suffix)) {
return true;
}
if (str.length() < suffix.length()) {
return false;
}

String lcStr = str.substring(str.length() - suffix.length())
.toLowerCase();
String lcSuffix = suffix.toLowerCase();
return lcStr.equals(lcSuffix);
}

/**
* Count the occurrences of the substring in string s.
*
* @param str
* string to search in. Return 0 if this is null.
* @param sub
* string to search for. Return 0 if this is null.
*/
public static int countOccurrencesOf(String str, String sub) {
if (str == null || sub == null || str.length() == 0
|| sub.length() == 0) {
return 0;
}
int count = 0, pos = 0, idx = 0;
while ((idx = str.indexOf(sub, pos)) != -1) {
++count;
pos = idx + sub.length();
}
return count;
}

/**
* Replace all occurences of a substring within a string with another
* string.
*
* @param inString
* String to examine
* @param oldPattern
* String to replace
* @param newPattern
* String to insert
* @return a String with the replacements
*/
public static String replaceplus(String inString, String oldPattern,
String newPattern) {
if (inString == null) {
return null;
}
if (oldPattern == null || newPattern == null) {
return inString;
}

StringBuffer sbuf = new StringBuffer();
// output StringBuffer we'll build up
int pos = 0; // our position in the old string
int index = inString.indexOf(oldPattern);
// the index of an occurrence we've found, or -1
int patLen = oldPattern.length();
while (index >= 0) {
sbuf.append(inString.substring(pos, index));
sbuf.append(newPattern);
pos = index + patLen;
index = inString.indexOf(oldPattern, pos);
}
sbuf.append(inString.substring(pos));

// remember to append any characters to the right of a match
return sbuf.toString();
}

/**
* Delete all occurrences of the given substring.
*
* @param pattern
* the pattern to delete all occurrences of
*/
public static String delete(String inString, String pattern) {
return replace(inString, pattern, "");
}

/**
* Delete any character in a given string.
*
* @param charsToDelete
* a set of characters to delete. E.g. "az\n" will delete 'a's,
* 'z's and new lines.
*/
public static String deleteAny(String inString, String charsToDelete) {
if (inString == null || charsToDelete == null) {
return inString;
}
StringBuffer out = new StringBuffer();
for (int i = 0; i < inString.length(); i++) {
char c = inString.charAt(i);
if (charsToDelete.indexOf(c) == -1) {
out.append(c);
}
}
return out.toString();
}

// ---------------------------------------------------------------------
// Convenience methods for working with formatted Strings
// ---------------------------------------------------------------------

/**
* Quote the given String with single quotes.
*
* @param str
* the input String (e.g. "myString")
* @return the quoted String (e.g. "'myString'"), or
* <code>null<code> if the input was <code>null</code>
*/
public static String quote(String str) {
return (str != null ? "'" + str + "'" : null);
}

/**
* Turn the given Object into a String with single quotes if it is a String;
* keeping the Object as-is else.
*
* @param obj
* the input Object (e.g. "myString")
* @return the quoted String (e.g. "'myString'"), or the input object as-is
* if not a String
*/
public static Object quoteIfString(Object obj) {
return (obj instanceof String ? quote((String) obj) : obj);
}

/**
* Unqualify a string qualified by a '.' dot character. For example,
* "this.name.is.qualified", returns "qualified".
*
* @param qualifiedName
* the qualified name
*/
public static String unqualify(String qualifiedName) {
return unqualify(qualifiedName, '.');
}

/**
* Unqualify a string qualified by a separator character. For example,
* "this:name:is:qualified" returns "qualified" if using a ':' separator.
*
* @param qualifiedName
* the qualified name
* @param separator
* the separator
*/
public static String unqualify(String qualifiedName, char separator) {
return qualifiedName
.substring(qualifiedName.lastIndexOf(separator) + 1);
}

/**
* Capitalize a <code>String</code>, changing the first letter to upper case
* as per {@link Character#toUpperCase(char)}. No other letters are changed.
*
* @param str
* the String to capitalize, may be <code>null</code>
* @return the capitalized String, <code>null</code> if null
*/
public static String capitalize(String str) {
return changeFirstCharacterCase(str, true);
}

/**
* Uncapitalize a <code>String</code>, changing the first letter to lower
* case as per {@link Character#toLowerCase(char)}. No other letters are
* changed.
*
* @param str
* the String to uncapitalize, may be <code>null</code>
* @return the uncapitalized String, <code>null</code> if null
*/
public static String uncapitalize(String str) {
return changeFirstCharacterCase(str, false);
}

private static String changeFirstCharacterCase(String str,
boolean capitalize) {
if (str == null || str.length() == 0) {
return str;
}
StringBuffer buf = new StringBuffer(str.length());
if (capitalize) {
buf.append(Character.toUpperCase(str.charAt(0)));
} else {
buf.append(Character.toLowerCase(str.charAt(0)));
}
buf.append(str.substring(1));
return buf.toString();
}

/**
* Extract the filename from the given path, e.g. "mypath/myfile.txt" ->
* "myfile.txt".
*
* @param path
* the file path (may be <code>null</code>)
* @return the extracted filename, or <code>null</code> if none
*/
public static String getFilename(String path) {
if (path == null) {
return null;
}
int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
return (separatorIndex != -1 ? path.substring(separatorIndex + 1)
: path);
}

/**
* Extract the filename extension from the given path, e.g.
* "mypath/myfile.txt" -> "txt".
*
* @param path
* the file path (may be <code>null</code>)
* @return the extracted filename extension, or <code>null</code> if none
*/
public static String getFilenameExtension(String path) {
if (path == null) {
return null;
}
int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
return (sepIndex != -1 ? path.substring(sepIndex + 1) : null);
}

/**
* Strip the filename extension from the given path, e.g.
* "mypath/myfile.txt" -> "mypath/myfile".
*
* @param path
* the file path (may be <code>null</code>)
* @return the path with stripped filename extension, or <code>null</code>
* if none
*/
public static String stripFilenameExtension(String path) {
if (path == null) {
return null;
}
int sepIndex = path.lastIndexOf(EXTENSION_SEPARATOR);
return (sepIndex != -1 ? path.substring(0, sepIndex) : path);
}

/**
* Apply the given relative path to the given path, assuming standard Java
* folder separation (i.e. "/" separators);
*
* @param path
* the path to start from (usually a full file path)
* @param relativePath
* the relative path to apply (relative to the full file path
* above)
* @return the full file path that results from applying the relative path
*/
public static String applyRelativePath(String path, String relativePath) {
int separatorIndex = path.lastIndexOf(FOLDER_SEPARATOR);
if (separatorIndex != -1) {
String newPath = path.substring(0, separatorIndex);
if (!relativePath.startsWith(FOLDER_SEPARATOR)) {
newPath += FOLDER_SEPARATOR;
}
return newPath + relativePath;
} else {
return relativePath;
}
}

/**
* Normalize the path by suppressing sequences like "path/.." and inner
* simple dots.
* <p>
* The result is convenient for path comparison. For other uses, notice that
* Windows separators ("\") are replaced by simple slashes.
*
* @param path
* the original path
* @return the normalized path
*/
public static String cleanPath(String path) {
String pathToUse = replace(path, WINDOWS_FOLDER_SEPARATOR,
FOLDER_SEPARATOR);

// Strip prefix from path to analyze, to not treat it as part of the
// first path element. This is necessary to correctly parse paths like
// "file:core/../core/io/Resource.class", where the ".." should just
// strip the first "core" directory while keeping the "file:" prefix.
int prefixIndex = pathToUse.indexOf(":");
String prefix = "";
if (prefixIndex != -1) {
prefix = pathToUse.substring(0, prefixIndex + 1);
pathToUse = pathToUse.substring(prefixIndex + 1);
}

String[] pathArray = delimitedListToStringArray(pathToUse,
FOLDER_SEPARATOR);
List pathElements = new LinkedList();
int tops = 0;

for (int i = pathArray.length - 1; i >= 0; i--) {
if (CURRENT_PATH.equals(pathArray[i])) {
// Points to current directory - drop it.
} else if (TOP_PATH.equals(pathArray[i])) {
// Registering top path found.
tops++;
} else {
if (tops > 0) {
// Merging path element with corresponding to top path.
tops--;
} else {
// Normal path element found.
pathElements.add(0, pathArray[i]);
}
}
}

// Remaining top paths need to be retained.
for (int i = 0; i < tops; i++) {
pathElements.add(0, TOP_PATH);
}

return prefix
+ collectionToDelimitedString(pathElements, FOLDER_SEPARATOR);
}

/**
* Compare two paths after normalization of them.
*
* @param path1
* First path for comparizon
* @param path2
* Second path for comparizon
* @return whether the two paths are equivalent after normalization
*/
public static boolean pathEquals(String path1, String path2) {
return cleanPath(path1).equals(cleanPath(path2));
}

/**
* Parse the given locale string into a <code>java.util.Locale</code>. This
* is the inverse operation of Locale's <code>toString</code>.
*
* @param localeString
* the locale string, following <code>java.util.Locale</code>'s
* toString format ("en", "en_UK", etc). Also accepts spaces as
* separators, as alternative to underscores.
* @return a corresponding Locale instance
*/
public static Locale parseLocaleString(String localeString) {
String[] parts = tokenizeToStringArray(localeString, "_ ", false, false);
String language = (parts.length > 0 ? parts[0] : "");
String country = (parts.length > 1 ? parts[1] : "");
String variant = (parts.length > 2 ? parts[2] : "");
return (language.length() > 0 ? new Locale(language, country, variant)
: null);
}

// ---------------------------------------------------------------------
// Convenience methods for working with String arrays
// ---------------------------------------------------------------------

/**
* Append the given String to the given String array, returning a new array
* consisting of the input array contents plus the given String.
*
* @param array
* the array to append to (can be <code>null</code>)
* @param str
* the String to append
* @return the new array (never <code>null</code>)
*/
public static String[] addStringToArray(String[] array, String str) {
if (array == null || array.length < 0) {
return new String[] { str };
}
String[] newArr = new String[array.length + 1];
System.arraycopy(array, 0, newArr, 0, array.length);
newArr[array.length] = str;
return newArr;
}

/**
* Turn given source String array into sorted array.
*
* @param array
* the source array
* @return the sorted array (never <code>null</code>)
*/
public static String[] sortStringArray(String[] array) {
if (array == null || array.length < 0) {
return new String[0];
}
Arrays.sort(array);
return array;
}

/**
* Copy the given Collection into a String array. The Collection must
* contain String elements only.
*
* @param collection
* the Collection to copy
* @return the String array (<code>null</code> if the Collection was
* <code>null</code> as well)
*/
public static String[] toStringArray(Collection collection) {
if (collection == null) {
return null;
}
return (String[]) collection.toArray(new String[collection.size()]);
}

/**
* Remove duplicate Strings from the given array. Also sorts the array, as
* it uses a TreeSet.
*
* @param array
* the String array
* @return an array without duplicates, in natural sort order
*/
public static String[] removeDuplicateStrings(String[] array) {
if (array == null || array.length < 0) {
return array;
}
Set set = new TreeSet();
for (int i = 0; i < array.length; i++) {
set.add(array[i]);
}
return toStringArray(set);
}

/**
* Split a String at the first occurrence of the delimiter. Does not include
* the delimiter in the result.
*
* @param toSplit
* the string to split
* @param delimiter
* to split the string up with
* @return a two element array with index 0 being before the delimiter, and
* index 1 being after the delimiter (neither element includes the
* delimiter); or <code>null</code> if the delimiter wasn't found in
* the given input String
*/
public static String[] split2(String toSplit, String delimiter) {
if (!hasLength(toSplit) || !hasLength(delimiter)) {
return null;
}
int offset = toSplit.indexOf(delimiter);
if (offset < 0) {
return null;
}
String beforeDelimiter = toSplit.substring(0, offset);
String afterDelimiter = toSplit.substring(offset + delimiter.length());
return new String[] { beforeDelimiter, afterDelimiter };
}

/**
* Take an array Strings and split each element based on the given
* delimiter. A <code>Properties</code> instance is then generated, with the
* left of the delimiter providing the key, and the right of the delimiter
* providing the value.
* <p>
* Will trim both the key and value before adding them to the
* <code>Properties</code> instance.
*
* @param array
* the array to process
* @param delimiter
* to split each element using (typically the equals symbol)
* @return a <code>Properties</code> instance representing the array
* contents, or <code>null</code> if the array to process was null
* or empty
*/
public static Properties splitArrayElementsIntoProperties(String[] array,
String delimiter) {
return splitArrayElementsIntoProperties(array, delimiter, null);
}

/**
* Take an array Strings and split each element based on the given
* delimiter. A <code>Properties</code> instance is then generated, with the
* left of the delimiter providing the key, and the right of the delimiter
* providing the value.
* <p>
* Will trim both the key and value before adding them to the
* <code>Properties</code> instance.
*
* @param array
* the array to process
* @param delimiter
* to split each element using (typically the equals symbol)
* @param charsToDelete
* one or more characters to remove from each element prior to
* attempting the split operation (typically the quotation mark
* symbol), or <code>null</code> if no removal should occur
* @return a <code>Properties</code> instance representing the array
* contents, or <code>null</code> if the array to process was null
* or empty
*/
public static Properties splitArrayElementsIntoProperties(String[] array,
String delimiter, String charsToDelete) {

if (array == null || array.length == 0) {
return null;
}

Properties result = new Properties();
for (int i = 0; i < array.length; i++) {
String element = array[i];
if (charsToDelete != null) {
element = deleteAny(array[i], charsToDelete);
}
String[] splittedElement = split(element, delimiter);
if (splittedElement == null) {
continue;
}
result.setProperty(splittedElement[0].trim(), splittedElement[1]
.trim());
}
return result;
}

/**
* Tokenize the given String into a String array via a StringTokenizer.
* Trims tokens and omits empty tokens.
* <p>
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
*
* @param str
* the String to tokenize
* @param delimiters
* the delimiter characters, assembled as String (each of those
* characters is individually considered as delimiter).
* @return an array of the tokens
* @see java.util.StringTokenizer
* @see java.lang.String#trim
* @see #delimitedListToStringArray
*/
public static String[] tokenizeToStringArray(String str, String delimiters) {
return tokenizeToStringArray(str, delimiters, true, true);
}

/**
* Tokenize the given String into a String array via a StringTokenizer.
* <p>
* The given delimiters string is supposed to consist of any number of
* delimiter characters. Each of those characters can be used to separate
* tokens. A delimiter is always a single character; for multi-character
* delimiters, consider using <code>delimitedListToStringArray</code>
*
* @param str
* the String to tokenize
* @param delimiters
* the delimiter characters, assembled as String (each of those
* characters is individually considered as delimiter)
* @param trimTokens
* trim the tokens via String's <code>trim</code>
* @param ignoreEmptyTokens
* omit empty tokens from the result array (only applies to
* tokens that are empty after trimming; StringTokenizer will not
* consider subsequent delimiters as token in the first place).
* @return an array of the tokens
* @see java.util.StringTokenizer
* @see java.lang.String#trim
* @see #delimitedListToStringArray
*/
public static String[] tokenizeToStringArray(String str, String delimiters,
boolean trimTokens, boolean ignoreEmptyTokens) {

StringTokenizer st = new StringTokenizer(str, delimiters);
List tokens = new ArrayList();
while (st.hasMoreTokens()) {
String token = st.nextToken();
if (trimTokens) {
token = token.trim();
}
if (!ignoreEmptyTokens || token.length() > 0) {
tokens.add(token);
}
}
return toStringArray(tokens);
}

/**
* Take a String which is a delimited list and convert it to a String array.
* <p>
* A single delimiter can consists of more than one character: It will still
* be considered as single delimiter string, rather than as bunch of
* potential delimiter characters - in contrast to
* <code>tokenizeToStringArray</code>.
*
* @param str
* the input String
* @param delimiter
* the delimiter between elements (this is a single delimiter,
* rather than a bunch individual delimiter characters)
* @return an array of the tokens in the list
* @see #tokenizeToStringArray
*/
public static String[] delimitedListToStringArray(String str,
String delimiter) {
if (str == null) {
return new String[0];
}
if (delimiter == null) {
return new String[] { str };
}

List result = new ArrayList();
if ("".equals(delimiter)) {
for (int i = 0; i < str.length(); i++) {
result.add(str.substring(i, i + 1));
}
} else {
int pos = 0;
int delPos = 0;
while ((delPos = str.indexOf(delimiter, pos)) != -1) {
result.add(str.substring(pos, delPos));
pos = delPos + delimiter.length();
}
if (str.length() > 0 && pos <= str.length()) {
// Add rest of String, but not in case of empty input.
result.add(str.substring(pos));
}
}
return toStringArray(result);
}

/**
* Convert a CSV list into an array of Strings.
*
* @param str
* CSV list
* @return an array of Strings, or the empty array if s is null
*/
public static String[] commaDelimitedListToStringArray(String str) {
return delimitedListToStringArray(str, ",");
}

/**
* Convenience method to convert a CSV string list to a set. Note that this
* will suppress duplicates.
*
* @param str
* CSV String
* @return a Set of String entries in the list
*/
public static Set commaDelimitedListToSet(String str) {
Set set = new TreeSet();
String[] tokens = commaDelimitedListToStringArray(str);
for (int i = 0; i < tokens.length; i++) {
set.add(tokens[i]);
}
return set;
}

/**
* Convenience method to return a String array as a delimited (e.g. CSV)
* String. E.g. useful for toString() implementations.
*
* @param arr
* array to display. Elements may be of any type (toString will
* be called on each element).
* @param delim
* delimiter to use (probably a ",")
*/
public static String arrayToDelimitedString(Object[] arr, String delim) {
if (arr == null) {
return "";
}

StringBuffer sb = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
if (i > 0) {
sb.append(delim);
}
sb.append(arr[i]);
}
return sb.toString();
}

/**
* Convenience method to return a Collection as a delimited (e.g. CSV)
* String. E.g. useful for toString() implementations.
*
* @param coll
* Collection to display
* @param delim
* delimiter to use (probably a ",")
* @param prefix
* string to start each element with
* @param suffix
* string to end each element with
*/
public static String collectionToDelimitedString(Collection coll,
String delim, String prefix, String suffix) {
if (coll == null) {
return "";
}

StringBuffer sb = new StringBuffer();
Iterator it = coll.iterator();
int i = 0;
while (it.hasNext()) {
if (i > 0) {
sb.append(delim);
}
sb.append(prefix).append(it.next()).append(suffix);
i++;
}
return sb.toString();
}

/**
* Convenience method to return a Collection as a delimited (e.g. CSV)
* String. E.g. useful for toString() implementations.
*
* @param coll
* Collection to display
* @param delim
* delimiter to use (probably a ",")
*/
public static String collectionToDelimitedString(Collection coll,
String delim) {
return collectionToDelimitedString(coll, delim, "", "");
}

/**
* Convenience method to return a String array as a CSV String. E.g. useful
* for toString() implementations.
*
* @param arr
* array to display. Elements may be of any type (toString will
* be called on each element).
*/
public static String arrayToCommaDelimitedString(Object[] arr) {
return arrayToDelimitedString(arr, ",");
}

/**
* Convenience method to return a Collection as a CSV String. E.g. useful
* for toString() implementations.
*
* @param coll
* Collection to display
*/
public static String collectionToCommaDelimitedString(Collection coll) {
return collectionToDelimitedString(coll, ",");
}

/**
* 中文转换
*
* @param source
* @return
*/
public static String[] getGBK(String[] source) {
if (source == null) {
return null;
}
String[] buffer = new String[source.length];
for (int i = 0; i < source.length; i++) {
buffer[i] = getGBK(source[i]);
}
return buffer;
}

public static String getGBK(String source) {
if (source == null) {
return null;
}
String target = null;
try {
byte[] b = source.getBytes("ISO8859_1");
target = new String(b, "GBK");
} catch (Exception e) {
}
return target;
}

public static String[] getISO8859_1(String[] source) {
String[] buffer = new String[source.length];
for (int i = 0; i < source.length; i++) {
buffer[i] = getISO8859_1(source[i]);
}
return buffer;
}

public static String getISO8859_1(String source) {
String target = null;
try {
byte[] b = source.getBytes("GBK");
target = new String(b, "ISO8859_1");
} catch (Exception e) {
}
return target;
}

/**
* 字符串替换
*
* @param mainStr
* @param oldStr
* @param newStr
* @return
*/
public static String replace2(String mainStr, String oldStr, String newStr) {
StringBuffer buffer = new StringBuffer(mainStr);
int index = 0;
int begin = 0;
while ((index = buffer.toString().indexOf(oldStr, begin)) > -1) {
buffer.replace(index, index + oldStr.length(), newStr);
begin = index + newStr.length();
}
return buffer.toString();
}

/**
* 用于对象的类型转换
*
* @param type
* @param var
* @return
* @throws SystemException
*/
public static Object convert(Class type, String var) throws Exception {
if (type.getName().equalsIgnoreCase("java.lang.String")) {
return var;
} else if (type.getName().equalsIgnoreCase("java.math.BigDecimal")) {
return new java.math.BigDecimal(var);
} else if (type.getName().equalsIgnoreCase("java.sql.Date")
|| type.getName().equalsIgnoreCase("java.util.Date")) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(var);
} catch (ParseException e) {
throw new Exception(e);
}
} else if (type.getName().equalsIgnoreCase("java.lang.Long")
|| type.getName().equalsIgnoreCase("long")) {
return new java.lang.Long(var);
} else if (type.getName().equalsIgnoreCase("java.lang.Integer")
|| type.getName().equalsIgnoreCase("int")) {
return new java.lang.Integer(var);
} else if (type.getName().equalsIgnoreCase("java.lang.Boolean")
|| type.getName().equalsIgnoreCase("boolean")) {
return new java.lang.Boolean(var);
} else {
return null;
}
}

/**
* 字符串是否包含在字符数组中
*
* @param value
* @param array
* @return
*/
public static boolean contains(String value, String[] array) {
if (array != null) {
for (int i = 0; i < array.length; ++i) {
if (value != null && array[i] != null && array[i].equals(value)) {
return true;
}
}
}
return false;
}

/**
* 字符串是否包含在字符数组中
*
* @param value
* @param array
* @return
*/
public static boolean contains(String mainStr, String subStr) {
int index = mainStr.indexOf(subStr);
boolean retflag = (index > -1) ? true : false;
return retflag;
}

/**
* 加密
*
* @param str
* @return
*/
public static String crypt(String str) {
try {
MessageDigest md = MessageDigest.getInstance("MD5"); // 所用的加密算法
md.update(str.getBytes());
byte[] digestArr = md.digest(); // 计算摘要,加密
String aaa = byte2hex(digestArr);
return aaa;
} catch (Exception e) {
return "error!";
}

}

/**
* 加密辅助
*
* @param b
* @return
*/

public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
// if(n<b.length-1)
// hs = hs + ":";
}
}
return hs.toUpperCase();
}

/**
* 生成随机数 flag为位数,如flag=8,则生成8位随机数
*
* @param flag
* @return
*/
public static String getRandom(int flag) {
int i;
String randomStr = "";
for (int j = 1; j < flag; j++) {
i = (int) (Math.random() * 10);
randomStr += String.valueOf(i);
}
return randomStr;
}

/**
* 字符数组转换成字符串
*
* @param array
* @param token
* @return
*/
public static String StringArrayToString(String[] array, String token) {
if (array != null) {
String separator = token == null ? "," : token;
StringBuffer buffer = new StringBuffer();
for (int i = 0; i < array.length; i++) {
if (i > 0) {
buffer.append(separator);
}
buffer.append(array[i]);
}
return buffer.toString();
}
return null;
}

/**
* 字符串转换成字符数组
*
* @param var
* @param token
* @return
*/
public static String[] StringToStringArray(String var, String token) {
String separator = token == null ? "," : token;
if (var != null) {
StringTokenizer st = new StringTokenizer(var, separator);
String[] buffer = new String[st.countTokens()];
int t = 0;
while (st.hasMoreTokens()) {
buffer[t] = st.nextToken();
t++;
}
return buffer;
}
return null;
}

/**
* 字符串处理,写SQL语句
*
* @param strSource
* @return
*/
public static String toSqlString(String strSource) {
String strResult;
if (strSource == null) {
strResult = "null";
} else {
strResult = replace(strSource, "'", "''");
strResult = replace(strResult, "&lt;", "<");
strResult = replace(strResult, "&gt;", ">");
strResult = "'" + strResult + "'";
}
return strResult;
}

/**
* 说明:用于html页面中'null'转换
*
* @param obj
* @param str
* @return
*/
public static String changeNullToStr(Object obj, String str) {
if (obj == null || obj.toString().equals("null")) {
return str;
} else {
return obj.toString();
}
}

/**
* 说明:用于html页面中'null'转换为""
*
* @param obj
* @return
*/
public static String changeNullToStr(Object obj) {
if (obj == null) {
return "";
} else {
return obj.toString();
}
}

/**
* 把字符串第一个字母转换成大写
*
* @param str
* @return
*/
public static String firstCharToUpperCase(String str) {
return str.substring(0, 1).toUpperCase() + str.substring(1);
}

/**
* 把字符串第一个字母转换成小写
*
* @param str
* @return
*/
public static String firstCharToLowerCase(String str) {
return str.substring(0, 1).toLowerCase() + str.substring(1);
}

/**
* 把字符串转换成clob
*
* @param str
* @return
* @throws SystemException
*/
/*
* @SuppressWarnings("deprecation") public static Clob
* converStringToClob(String str) throws SystemException { if (str == null)
* { return null; } try { Clob clob = CLOB.empty_lob(); ((Datum)
* clob).setBytes(str.getBytes()); return clob; } catch (SQLException e) {
* throw new SystemException(e); } }
*/
/**
* 把clob转换成字符串
*
* @param clob
* @return
* @throws SystemException
*/
/*
* public static String converClobToString(Clob clob) throws SystemException
* { CLOB clobvalue = (CLOB) clob; if (clob == null) { return null; } byte[]
* bytes = clobvalue.getBytes(); return bytes == null ? null : new
* String(bytes); }
*/
/**
* 分割字串
*
* @param source
* 原始字符
* @param div
* 分割符
* @return 字符串数组
*/
public static String[] split(String source, String div) {
int arynum = 0, intIdx = 0, intIdex = 0, div_length = div.length();
if (source.compareTo("") != 0) {
if (source.indexOf(div) != -1) {
intIdx = source.indexOf(div);
for (int intCount = 1;; intCount++) {
if (source.indexOf(div, intIdx + div_length) != -1) {
intIdx = source.indexOf(div, intIdx + div_length);
arynum = intCount;
} else {
arynum += 2;
break;
}
}
} else {
arynum = 1;
}
} else {
arynum = 0;

}
intIdx = 0;
intIdex = 0;
String[] returnStr = new String[arynum];

if (source.compareTo("") != 0) {
if (source.indexOf(div) != -1) {
intIdx = (int) source.indexOf(div);
returnStr[0] = (String) source.substring(0, intIdx);
for (int intCount = 1;; intCount++) {
if (source.indexOf(div, intIdx + div_length) != -1) {
intIdex = (int) source
.indexOf(div, intIdx + div_length);
returnStr[intCount] = (String) source.substring(intIdx
+ div_length, intIdex);
intIdx = (int) source.indexOf(div, intIdx + div_length);
} else {
returnStr[intCount] = (String) source.substring(intIdx
+ div_length, source.length());
break;
}
}
} else {
returnStr[0] = (String) source.substring(0, source.length());
return returnStr;
}
} else {
return returnStr;
}
return returnStr;
}

/*
* 使用方法:主要为替换sql语句中的?. s:要替换的原sql splitchar:要替换的字符中,在此为"?"
* parms[]:长度必需和?个数一样,
*/
public static String replaceSqlByArray(String sql, String splitchar,
Object parms[]) {
String afterSplits[] = StringUtils.split(sql, splitchar);
String retStr = "";
if (parms.length == afterSplits.length - 1) {
for (int i = 0; i < parms.length; i++) {
retStr = retStr + afterSplits[i] + parms[i].toString();
}
} else {
log.debug("sql中的?和参数数据中的个数不相符");
}
return retStr;
}

/**
* 将字符串格式成html格式
*
* @param str
* 被转换的字符串
* @return String if str is not null ,otherwise return null
*/
public static String formatStringToHtml(String str) {
if (str == null) {
return "";
}
str = replace(str, "\n", "<br>");
str = replace(str, "\'", "\\\'");
str = replace(str, "\"", "\\\"");
str = replace(str, " ", "&nbsp;");
return str;
}

/**
* 说明:开始日期与结束日期输入是否合法,true为合法
*
* @param start_time
* @param end_time
* @return
* @throws SystemException
*/
/*
* public static boolean dateIsLegality(DateElement start_time, DateElement
* end_time) throws SystemException { if (start_time.getValue() != null &&
* end_time.getValue() != null) { //为正确的日期格式 if (start_time.validate() &&
* end_time.validate()) { long start = start_time.getDateValue().getTime();
* long end = end_time.getDateValue().getTime(); if
* (start_time.getDay().getValue() != null && end_time.getDay().getValue()
* != null) { if (start - end >= 0) { return false; } } else { if (start -
* end > 0) { return false; } } } } return true; }
*/
/**
* 判断字符串是否为null或者空。
*
* @param str
* 待判断的字符串
* @return boolean 判断结果
*/
public static boolean isBlank(String str) {
return (str == null) || (str.equals(""));
}

/**
* 从HttpServletRequest对象中取字符串数组。
*
* @param oRequest
* HttpServletRequest对象
* @param strParamName
* 参数名
* @param strDefaultValue
* 默认值
* @return 字符串数组
*/
public static String[] getStringArray(HttpServletRequest oRequest,
String strParamName, String strDefaultValue) {
if (oRequest == null || StringUtils.isBlank(strParamName)) {
return null;
}
String[] strParameterValues = oRequest.getParameterValues(strParamName);
if (strParameterValues == null) {
strParameterValues = new String[0];
}
for (int i = 0; i < strParameterValues.length; i++) {
if (strParameterValues[i] == null
|| strParameterValues[i].equals("")) {
strParameterValues[i] = strDefaultValue;
}
}
return strParameterValues;
}

/**
* 大写字母转换为小写字母或小写转换为大写,flag=1转换为大写,flag=2转换为小写
*
* @param str
* @param flag
* @return
*/
public static String capitalToLowercase(String str, int flag) {
String[] lowercass = { "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" };
String[] capital = { "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" };

StringBuffer sb = new StringBuffer();
for (int i = 0; i < str.length(); i++) {
String sub_str = String.valueOf(str.charAt(i));
// 转换为小写
if (flag == 1) {
for (int j = 0; j < lowercass.length; j++) {
String replace_str = lowercass[j];
if (sub_str.equalsIgnoreCase(replace_str)) {
sb.append(replace_str);
}
}
}
// 转换为大写
else if (flag == 2) {
for (int j = 0; j < capital.length; j++) {
String replace_str = capital[j];
if (sub_str.equalsIgnoreCase(replace_str)) {
sb.append(replace_str);
}
}
}
}
return sb.toString();
}



  评论这张
 
阅读(1416)| 评论(0)
推荐 转载

历史上的今天

在LOFTER的更多文章

评论

<#--最新日志,群博日志--> <#--推荐日志--> <#--引用记录--> <#--博主推荐--> <#--随机阅读--> <#--首页推荐--> <#--历史上的今天--> <#--被推荐日志--> <#--上一篇,下一篇--> <#-- 热度 --> <#-- 网易新闻广告 --> <#--右边模块结构--> <#--评论模块结构--> <#--引用模块结构--> <#--博主发起的投票-->
 
 
 
 
 
 
 
 
 
 
 
 
 
 

页脚

网易公司版权所有 ©1997-2017