📄 stringutils.java
字号:
*/
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.
*/
@SuppressWarnings("unchecked")
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();
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, "<", "<");
string = replace(string, ">", ">");
string = replace(string, """, "\"");
return replace(string, "&", "&");
}
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.
*/
@SuppressWarnings("unchecked")
public static final String collectionToString(Collection c, String spilt) {
if (c == null) {
return null;
}
if (spilt == null) {
return null;
}
String ret = "";
ArrayList 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();
}
@SuppressWarnings("finally")
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 getCurrTime() {
Date now = new Date();
SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");
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) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -