?? stringutils.java
字號:
/*
* StringUtils.java
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Library General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*
* Author: Winter Lau (javayou@gmail.com)
* http://dlog4j.sourceforge.net
*/
package com.liusoft.dlog4j.util;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import org.htmlparser.Node;
import org.htmlparser.NodeFilter;
import org.htmlparser.Parser;
import org.htmlparser.util.NodeList;
/**
* 字符串工具集合
* @author Winter Lau
*/
public class StringUtils extends org.apache.commons.lang.StringUtils {
/**
* 如果系統中存在舊版本的數據,則此值不能修改,否則在進行密碼解析的時候出錯
*/
private static final String PASSWORD_CRYPT_KEY = "__jDlog_";
private final static String DES = "DES";
private final static String ISO8859_1 = "8859_1";
private final static NodeFilter nodeFilter = new NodeFilter() {
public boolean accept(Node node) {
return true;
}
};
/**
* retrive the extend name of the given filename
* @param fn
* @return
*/
public static String getFileExtend(String fn){
if(isEmpty(fn))
return null;
int idx = fn.lastIndexOf('.')+1;
if(idx==0 || idx >= fn.length())
return null;
return fn.substring(idx);
}
/**
* 將字符串用ch分割并放入隊列
* @param tags
* @param ch
* @return
*/
public static List stringToList(String tags, String ch){
if(tags==null)
return null;
ArrayList tagList = new ArrayList();
StringTokenizer st = new StringTokenizer(tags, ch);
while(st.hasMoreElements()){
tagList.add(st.nextToken());
}
return tagList;
}
/**
* 將字符串用空格分割并放入隊列
* @param tags
* @return
*/
public static List stringToList(String tags){
if(tags==null)
return null;
ArrayList tagList = new ArrayList();
StringTokenizer st = new StringTokenizer(tags);
while(st.hasMoreElements()){
tagList.add(st.nextToken());
}
return tagList;
}
/**
* BASE64編碼
* @param s
* @return String
*/
public static byte[] enBASE64(byte[] bytes){
return Base64Code.encode(bytes);
}
/**
* BASE64反編碼
* @param bytes
* @return byte[]
*/
public static byte[] deBASE64(byte[] bytes){
return Base64Code.decode(bytes);
}
/**
* BASE64編碼
* @param s
* @return String
*/
public static String enBASE64(String s) {
if (s != null) {
byte abyte0[] = s.getBytes();
abyte0 = Base64Code.encode(abyte0);
s = new String(abyte0);
return s;
}
return null;
}
/**
* BASE64反編碼
* @param s
* @return String
*/
public static String deBASE64(String s) {
if (s != null) {
byte abyte0[] = s.getBytes();
abyte0 = Base64Code.decode(abyte0);
s = new String(abyte0);
abyte0 = null;
return s;
}
return null;
}
/**
* HTML輸出內容格式轉換
* @param content
* @return
*/
public static String formatContent(String content) {
if(content==null)
return "";
String randomStr = String.valueOf(System.currentTimeMillis());
String html = StringUtils.replace(content," ",randomStr);
html = StringUtils.replace(html, "&", "&");
html = StringUtils.replace(html, "'", "'");
html = StringUtils.replace(html, "\"", """);
html = StringUtils.replace(html, "\t", " ");// 替換跳格
html = StringUtils.replace(html, " ", " ");// 替換空格
html = StringUtils.replace(html, "<", "<");
html = StringUtils.replace(html, ">", ">");
return StringUtils.replace(html,randomStr," ").trim();
}
/**
* 抽取純文本信息
* @param inputHtml
* @return
*/
public static String extractText(String inputHtml) throws Exception {
StringBuffer text = new StringBuffer();
Parser parser = new Parser();
parser.setInputHTML(new String(inputHtml.getBytes(),ISO8859_1));
//Parser parser = Parser.createParser(new String(inputHtml.getBytes(),ISO8859_1));
//遍歷所有的節點
NodeList nodes = parser.extractAllNodesThatMatch(nodeFilter);
for(int i=0;i<nodes.size();i++){
Node node = nodes.elementAt(i);
text.append(new String(node.toPlainTextString().getBytes(ISO8859_1)));
}
return text.toString();
}
/**
* 判斷是不是一個合法的電子郵件地址
* @param email
* @return
*/
public static boolean isEmail(String email){
if(email==null)
return false;
email = email.trim();
if(email.indexOf(' ')!=-1)
return false;
int idx = email.indexOf('@');
if(idx==-1 || idx==0 || (idx+1)==email.length())
return false;
if(email.indexOf('@', idx+1)!=-1)
return false;
if(email.indexOf('.')==-1)
return false;
return true;
/*
Pattern emailer;
if(emailer==null){
String check = "^([a-z0-9A-Z]+[-|\\._]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";
emailer = Pattern.compile(check);
}
Matcher matcher = emailer.matcher(email);
return matcher.matches();
*/
}
/**
* 判斷字符串是否是一個IP地址
* @param addr
* @return
*/
public static boolean isIPAddr(String addr){
if(isEmpty(addr))
return false;
String[] ips = split(addr, '.');
if(ips.length != 4)
return false;
try{
int ipa = Integer.parseInt(ips[0]);
int ipb = Integer.parseInt(ips[1]);
int ipc = Integer.parseInt(ips[2]);
int ipd = Integer.parseInt(ips[3]);
return ipa >= 0 && ipa <= 255 && ipb >= 0 && ipb <=255 && ipc >= 0
&& ipc <= 255 && ipd >= 0 && ipd <=255;
}catch(Exception e){}
return false;
}
/**
* 加密
* @param src 數據源
* @param key 密鑰,長度必須是8的倍數
* @return 返回加密后的數據
* @throws Exception
*/
public static byte[] encrypt(byte[] src, byte[] key)
throws Exception {
// DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密匙數據創建DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 創建一個密匙工廠,然后用它把DESKeySpec轉換成
// 一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成加密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher對象
cipher.init(Cipher.ENCRYPT_MODE, securekey, sr);
// 現在,獲取數據并加密
// 正式執行加密操作
return cipher.doFinal(src);
}
/**
* 解密
* @param src 數據源
* @param key 密鑰,長度必須是8的倍數
* @return 返回解密后的原始數據
* @throws Exception
*/
public static byte[] decrypt(byte[] src, byte[] key)
throws Exception {
// DES算法要求有一個可信任的隨機數源
SecureRandom sr = new SecureRandom();
// 從原始密匙數據創建一個DESKeySpec對象
DESKeySpec dks = new DESKeySpec(key);
// 創建一個密匙工廠,然后用它把DESKeySpec對象轉換成
// 一個SecretKey對象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey securekey = keyFactory.generateSecret(dks);
// Cipher對象實際完成解密操作
Cipher cipher = Cipher.getInstance(DES);
// 用密匙初始化Cipher對象
cipher.init(Cipher.DECRYPT_MODE, securekey, sr);
// 現在,獲取數據并解密
// 正式執行解密操作
return cipher.doFinal(src);
}
/**
* 數據解密
* @param data
* @param key 密鑰
* @return
* @throws Exception
*/
public final static String decrypt(String data, String key){
if(data!=null)
try {
return new String(decrypt(hex2byte(data.getBytes()),key.getBytes()));
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 數據加密
* @param data
* @param key 密鑰
* @return
* @throws Exception
*/
public final static String encrypt(String data, String key){
if(data!=null)
try {
return byte2hex(encrypt(data.getBytes(),key.getBytes()));
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 密碼解密
* @param data
* @return
* @throws Exception
*/
public final static String decryptPassword(String data){
if(data!=null)
try {
return new String(decrypt(hex2byte(data.getBytes()),PASSWORD_CRYPT_KEY.getBytes()));
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 密碼加密
* @param password
* @return
* @throws Exception
*/
public final static String encryptPassword(String password){
if(password!=null)
try {
return byte2hex(encrypt(password.getBytes(),PASSWORD_CRYPT_KEY.getBytes()));
}catch(Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 二行制轉字符串
* @param b
* @return
*/
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; b!=null && n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1)
hs = hs + "0" + stmp;
else
hs = hs + stmp;
}
return hs.toUpperCase();
}
public static byte[] hex2byte(byte[] b) {
if((b.length%2)!=0)
throw new IllegalArgumentException("長度不是偶數");
byte[] b2 = new byte[b.length/2];
for (int n = 0; n < b.length; n+=2) {
String item = new String(b,n,2);
b2[n/2] = (byte)Integer.parseInt(item,16);
}
return b2;
?? 快捷鍵說明
復制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -