⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 stringutils.java

📁 个人Blog java编写的Blog可以直接使用!
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/*
 *  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, "<", "&lt;");
		html = StringUtils.replace(html, ">", "&gt;");
		return StringUtils.replace(html,randomStr,"&nbsp;").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 + -