您的位置:首页 > 编程语言 > Java开发

Java常用工具类总结(二)

2015-12-30 14:06 525 查看
1.字符编码工具类

package com.gootrip.util;
import java.io.UnsupportedEncodingException;

/**
* <p>Title:字符编码工具类 </p>
* <p>Description:  </p>
* <p>Copyright:  Copyright (c) 2007</p>
* <p>Company:  </p>
* @author:
* @version 1.0
*/
public class CharTools {

/**
* 转换编码 ISO-8859-1到GB2312
* @param text
* @return
*/
public static final String ISO2GB(String text) {
String result = "";
try {
result = new String(text.getBytes("ISO-8859-1"), "GB2312");
}
catch (UnsupportedEncodingException ex) {
result = ex.toString();
}
return result;
}

/**
* 转换编码 GB2312到ISO-8859-1
* @param text
* @return
*/
public static final String GB2ISO(String text) {
String result = "";
try {
result = new String(text.getBytes("GB2312"), "ISO-8859-1");
}
catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
}
return result;
}
/**
* Utf8URL编码
* @param s
* @return
*/
public static final String Utf8URLencode(String text) {
StringBuffer result = new StringBuffer();

for (int i = 0; i < text.length(); i++) {

char c = text.charAt(i);
if (c >= 0 && c <= 255) {
result.append(c);
}else {

byte[] b = new byte[0];
try {
b = Character.toString(c).getBytes("UTF-8");
}catch (Exception ex) {
}

for (int j = 0; j < b.length; j++) {
int k = b[j];
if (k < 0) k += 256;
result.append("%" + Integer.toHexString(k).toUpperCase());
}

}
}

return result.toString();
}

/**
* Utf8URL解码
* @param text
* @return
*/
public static final String Utf8URLdecode(String text) {
String result = "";
int p = 0;

if (text!=null && text.length()>0){
text = text.toLowerCase();
p = text.indexOf("%e");
if (p == -1) return text;

while (p != -1) {
result += text.substring(0, p);
text = text.substring(p, text.length());
if (text == "" || text.length() < 9) return result;

result += CodeToWord(text.substring(0, 9));
text = text.substring(9, text.length());
p = text.indexOf("%e");
}

}

return result + text;
}

/**
* utf8URL编码转字符
* @param text
* @return
*/
private static final String CodeToWord(String text) {
String result;

if (Utf8codeCheck(text)) {
byte[] code = new byte[3];
code[0] = (byte) (Integer.parseInt(text.substring(1, 3), 16) - 256);
code[1] = (byte) (Integer.parseInt(text.substring(4, 6), 16) - 256);
code[2] = (byte) (Integer.parseInt(text.substring(7, 9), 16) - 256);
try {
result = new String(code, "UTF-8");
}catch (UnsupportedEncodingException ex) {
result = null;
}
}
else {
result = text;
}

return result;
}

/**
* 编码是否有效
* @param text
* @return
*/
private static final boolean Utf8codeCheck(String text){
String sign = "";
if (text.startsWith("%e"))
for (int i = 0, p = 0; p != -1; i++) {
p = text.indexOf("%", p);
if (p != -1)
p++;
sign += p;
}
return sign.equals("147-1");
}

/**
* 判断是否Utf8Url编码
* @param text
* @return
*/
public static final boolean isUtf8Url(String text) {
text = text.toLowerCase();
int p = text.indexOf("%");
if (p != -1 && text.length() - p > 9) {
text = text.substring(p, p + 9);
}
return Utf8codeCheck(text);
}

/**
* 测试
* @param args
*/
public static void main(String[] args) {

//CharTools charTools = new CharTools();

String url;

url = "http://www.google.com/search?hl=zh-CN&newwindow=1&q=%E4%B8%AD%E5%9B%BD%E5%A4%A7%E7%99%BE%E7%A7%91%E5%9C%A8%E7%BA%BF%E5%85%A8%E6%96%87%E6%A3%80%E7%B4%A2&btnG=%E6%90%9C%E7%B4%A2&lr=";
if(CharTools.isUtf8Url(url)){
System.out.println(CharTools.Utf8URLdecode(url));
}else{
//System.out.println(URLDecoder.decode(url));
}

url = "http://www.baidu.com/baidu?word=%D6%D0%B9%FA%B4%F3%B0%D9%BF%C6%D4%DA%CF%DF%C8%AB%CE%C4%BC%EC%CB%F7&tn=myie2dg";
if(CharTools.isUtf8Url(url)){
System.out.println(CharTools.Utf8URLdecode(url));
}else{
//System.out.println(URLDecoder.decode(url));
}

}

}


2.读取配置文件

/**
* 读取配置文件
*/
package com.gootrip.util;

import java.io.File;
import java.net.URL;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationFactory;

/**
* @author advance
*
*/
public class ConfigHelper {
public ConfigHelper(){
}
/**
* 读取配置文件
* @param strfile
* @return
*/
public static Configuration getConfig(String strfile){
Configuration config = null;
try {
ConfigurationFactory factory = new ConfigurationFactory(strfile);
//			URL configURL = new File(strfile).toURL();
//			factory.setConfigurationFileName(configURL.toString());
config = factory.getConfiguration();
} catch (Exception e) {
e.printStackTrace();
}
return config;
}
/**
* @param args
*/
public static void main(String[] args) {
//ConfigHelper ch = new ConfigHelper();
//ch.test();
try{
Configuration config = getConfig("config.xml");
String backColor = config.getString("colors.background");
System.out.println("color: " + backColor);
config = null;
}catch(Exception e){
e.printStackTrace();
}
}

}


3.获取最大序列数

package com.gootrip.util;

import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
/**
* <p>Title: 计数器类</p>
* <p>Description: 获取最大序列数</p>
* <p>Copyright: Copyright (c) 2006</p>
* <p>Company: </p>
* @author advance.wu
* @version 1.0
*
* sql:
*
* CREATE TABLE `tblserial` (
`tablename` varchar(100) NOT NULL default '',
`serialno` int(11) NOT NULL default '0',
PRIMARY KEY  (`tablename`)
)
*/

public class Counter {
private static Counter counter = new Counter();
private Counter() {
}
public static Counter getInstance(){
return counter;
}
/**
* 获取最大序列号
* @param strTable 表名
* @param con 数据库链接
* @return
*/
public synchronized long nextSerial(String strTable,Connection con){
String strSQL = null;
long serialno = 0;
Statement stmt = null;
try {
strSQL = "select serialno from tblserial where tablename='" + strTable + "'";
stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(strSQL);
if (rs.next())
serialno = rs.getLong(1);
strSQL = "update tblserial set serialno = serialno + 1 where tablename='" + strTable + "'";
stmt.execute(strSQL);
rs.close();
rs = null;
serialno ++;
}
catch (Exception ex) {

}finally{
if (stmt != null)
try {
stmt.close();
stmt = null;
}
catch (Exception ex) {}
}
return serialno;
}
}


4.Java编程中WEB开发常用到的一些工具

package com.gootrip.util;

/**
* 此类中收集Java编程中WEB开发常用到的一些工具。
* 为避免生成此类的实例,构造方法被申明为private类型的。
* @author
*/
import java.io.IOException;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.util.Date;

public class CTool {
/**
* 私有构造方法,防止类的实例化,因为工具类不需要实例化。
*/
private CTool() {
}

/**
<pre>
* 例:
* String strVal="This is a dog";
* String strResult=CTools.replace(strVal,"dog","cat");
* 结果:
* strResult equals "This is cat"
*
* @param strSrc 要进行替换操作的字符串
* @param strOld 要查找的字符串
* @param strNew 要替换的字符串
* @return 替换后的字符串
<pre>
*/
public static final String replace(String strSrc, String strOld,
String strNew) {
if (strSrc == null || strOld == null || strNew == null)
return "";

int i =
4000
0;

if (strOld.equals(strNew)) //避免新旧字符一样产生死循环
return strSrc;

if ((i = strSrc.indexOf(strOld, i)) >= 0) {
char[] arr_cSrc = strSrc.toCharArray();
char[] arr_cNew = strNew.toCharArray();

int intOldLen = strOld.length();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
buf.append(arr_cSrc, 0, i).append(arr_cNew);

i += intOldLen;
int j = i;

while ((i = strSrc.indexOf(strOld, i)) > 0) {
buf.append(arr_cSrc, j, i - j).append(arr_cNew);
i += intOldLen;
j = i;
}

buf.append(arr_cSrc, j, arr_cSrc.length - j);

return buf.toString();
}

return strSrc;
}

/**
* 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串
* 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&'
* @param strSrc 要进行替换操作的字符串
* @return 替换特殊字符后的字符串
* @since  1.0
*/

public static String htmlEncode(String strSrc) {
if (strSrc == null)
return "";

char[] arr_cSrc = strSrc.toCharArray();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
char ch;

for (int i = 0; i < arr_cSrc.length; i++) {
ch = arr_cSrc[i];

if (ch == '<')
buf.append("<");
else if (ch == '>')
buf.append(">");
else if (ch == '"')
buf.append(""");
else if (ch == '\'')
buf.append("'");
else if (ch == '&')
buf.append("&");
else
buf.append(ch);
}

return buf.toString();
}

/**
* 用于将字符串中的特殊字符转换成Web页中可以安全显示的字符串
* 可对表单数据据进行处理对一些页面特殊字符进行处理如'<','>','"',''','&'
* @param strSrc 要进行替换操作的字符串
* @param quotes 为0时单引号和双引号都替换,为1时不替换单引号,为2时不替换双引号,为3时单引号和双引号都不替换
* @return 替换特殊字符后的字符串
* @since  1.0
*/
public static String htmlEncode(String strSrc, int quotes) {

if (strSrc == null)
return "";
if (quotes == 0) {
return htmlEncode(strSrc);
}

char[] arr_cSrc = strSrc.toCharArray();
StringBuffer buf = new StringBuffer(arr_cSrc.length);
char ch;

for (int i = 0; i < arr_cSrc.length; i++) {
ch = arr_cSrc[i];
if (ch == '<')
buf.append("<");
else if (ch == '>')
buf.append(">");
else if (ch == '"' && quotes == 1)
buf.append(""");
else if (ch == '\'' && quotes == 2)
buf.append("'");
else if (ch == '&')
buf.append("&");
else
buf.append(ch);
}

return buf.toString();
}

/**
* 和htmlEncode正好相反
* @param strSrc 要进行转换的字符串
* @return 转换后的字符串
* @since  1.0
*/
public static String htmlDecode(String strSrc) {
if (strSrc == null)
return "";
strSrc = strSrc.replaceAll("<", "<");
strSrc = strSrc.replaceAll(">", ">");
strSrc = strSrc.replaceAll(""", "\"");
strSrc = strSrc.replaceAll("'", "'");
strSrc = strSrc.replaceAll("&", "&");
return strSrc;
}

/**
* 在将数据存入数据库前转换
* @param strVal 要转换的字符串
* @return 从“ISO8859_1”到“GBK”得到的字符串
* @since  1.0
*/
public static String toChinese(String strVal) {
try {
if (strVal == null) {
return "";
} else {
strVal = strVal.trim();
strVal = new String(strVal.getBytes("ISO8859_1"), "GBK");
return strVal;
}
} catch (Exception exp) {
return "";
}
}
/**
* 编码转换 从UTF-8到GBK
* @param strVal
* @return
*/
public static String toGBK(String strVal) {
try {
if (strVal == null) {
return "";
} else {
strVal = strVal.trim();
strVal = new String(strVal.getBytes("UTF-8"), "GBK");
return strVal;
}
} catch (Exception exp) {
return "";
}
}

/**
* 将数据从数据库中取出后转换   *
* @param strVal 要转换的字符串
* @return 从“GBK”到“ISO8859_1”得到的字符串
* @since  1.0
*/
public static String toISO(String strVal) {
try {
if (strVal == null) {
return "";
} else {
strVal = new String(strVal.getBytes("GBK"), "ISO8859_1");
return strVal;
}
} catch (Exception exp) {
return "";
}
}
public static String gbk2UTF8(String strVal) {
try {
if (strVal == null) {
return "";
} else {
strVal = new String(strVal.getBytes("GBK"), "UTF-8");
return strVal;
}
} catch (Exception exp) {
return "";
}
}
public static String ISO2UTF8(String strVal) {
try {
if (strVal == null) {
return "";
} else {
strVal = new String(strVal.getBytes("ISO-8859-1"), "UTF-8");
return strVal;
}
} catch (Exception exp) {
return "";
}
}
public static String UTF82ISO(String strVal) {
try {
if (strVal == null) {
return "";
} else {
strVal = new String(strVal.getBytes("UTF-8"), "ISO-8859-1");
return strVal;
}
} catch (Exception exp) {
return "";
}
}

/**
*显示大文本块处理(将字符集转成ISO)
*@deprecated
*@param str 要进行转换的字符串
*@return 转换成html可以正常显示的字符串
*/
public static String toISOHtml(String str) {
return toISO(htmlDecode(null2Blank((str))));
}

/**
*实际处理 return toChineseNoReplace(null2Blank(str));
*主要应用于老牛的信息发布
*@param str 要进行处理的字符串
*@return 转换后的字符串
*@see fs_com.utils.CTools#toChinese
*@see fs_com.utils.CTools#null2Blank
*/
public static String toChineseAndHtmlEncode(String str, int quotes) {
return htmlEncode(toChinese(str), quotes);
}

/**
*把null值和""值转换成 
*主要应用于页面表格格的显示
*@param str 要进行处理的字符串
*@return 转换后的字符串
*/
public static String str4Table(String str) {
if (str == null)
return " ";
else if (str.equals(""))
return " ";
else
return str;
}

/**
* String型变量转换成int型变量
* @param str 要进行转换的字符串
* @return intVal 如果str不可以转换成int型数据,返回-1表示异常,否则返回转换后的值
* @since  1.0
*/
public static int str2Int(String str) {
int intVal;

try {
intVal = Integer.parseInt(str);
} catch (Exception e) {
intVal = 0;
}

return intVal;
}

public static double str2Double(String str) {
double dVal = 0;

try {
dVal = Double.parseDouble(str);
} catch (Exception e) {
dVal = 0;
}

return dVal;
}

public static long str2Long(String str) {
long longVal = 0;

try {
longVal = Long.parseLong(str);
} catch (Exception e) {
longVal = 0;
}

return longVal;
}

public static float stringToFloat(String floatstr) {
Float floatee;
floatee = Float.valueOf(floatstr);
return floatee.floatValue();
}

//change the float type to the string type
public static String floatToString(float value) {
Float floatee = new Float(value);
return floatee.toString();
}

/**
*int型变量转换成String型变量
*@param intVal 要进行转换的整数
*@return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
*/
/**
*int型变量转换成String型变量
*@param intVal 要进行转换的整数
*@return str 如果intVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
*/
public static String int2Str(int intVal) {
String str;

try {
str = String.valueOf(intVal);
} catch (Exception e) {
str = "";
}

return str;
}

/**
*long型变量转换成String型变量
*@param longVal 要进行转换的整数
*@return str 如果longVal不可以转换成String型数据,返回空值表示异常,否则返回转换后的值
*/

public static String long2Str(long longVal) {
String str;

try {
str = String.valueOf(longVal);
} catch (Exception e) {
str = "";
}

return str;
}

/**
*null 处理
*@param str 要进行转换的字符串
*@return 如果str为null值,返回空串"",否则返回str
*/
public static String null2Blank(String str) {
if (str == null)
return "";
else
return str;
}

/**
*null 处理
*@param d 要进行转换的日期对像
*@return 如果d为null值,返回空串"",否则返回d.toString()
*/

public static String null2Blank(Date d) {
if (d == null)
return "";
else
return d.toString();
}

/**
*null 处理
*@param str 要进行转换的字符串
*@return 如果str为null值,返回空串整数0,否则返回相应的整数
*/
public static int null2Zero(String str) {
int intTmp;
intTmp = str2Int(str);
if (intTmp == -1)
return 0;
else
return intTmp;
}
/**
* 把null转换为字符串"0"
* @param str
* @return
*/
public static String null2SZero(String str) {
str = CTool.null2Blank(str);
if (str.equals(""))
return "0";
else
return str;
}

/**
* sql语句 处理
* @param sql 要进行处理的sql语句
* @param dbtype 数据库类型
* @return 处理后的sql语句
*/
public static String sql4DB(String sql, String dbtype) {
if (!dbtype.equalsIgnoreCase("oracle")) {
sql = CTool.toISO(sql);
}
return sql;
}

/**
* 对字符串进行md5加密
* @param s 要加密的字符串
* @return md5加密后的字符串
*/
public final static String MD5(String s) {
char hexDigits[] = {
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd',
'e', 'f'};
try {
byte[] strTemp = s.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
return null;
}
}
/**
* 字符串从GBK编码转换为Unicode编码
* @param text
* @return
*/
public static String StringToUnicode(String text) {
String result = "";
int input;
StringReader isr;
try {
isr = new StringReader(new String(text.getBytes(), "GBK"));
} catch (UnsupportedEncodingException e) {
return "-1";
}
try {
while ((input = isr.read()) != -1) {
result = result + "&#x" + Integer.toHexString(input) + ";";

}
} catch (IOException e) {
return "-2";
}
isr.close();
return result;

}
/**
*
* @param inStr
* @return
*/
public static String gb2utf(String inStr) {
char temChr;
int ascInt;
int i;
String result = new String("");
if (inStr == null) {
inStr = "";
}
for (i = 0; i < inStr.length(); i++) {
temChr = inStr.charAt(i);
ascInt = temChr + 0;
//System.out.println("1=="+ascInt);
//System.out.println("1=="+Integer.toBinaryString(ascInt));
if( Integer.toHexString(ascInt).length() > 2 ) {
result = result + "&#x" + Integer.toHexString(ascInt) + ";";
}
else
{
result = result + temChr;
}

}
return result;
}
/**
* This method will encode the String to unicode.
*
* @param gbString
* @return
*/

//代码:--------------------------------------------------------------------------------
public static String gbEncoding(final String gbString) {
char[] utfBytes = gbString.toCharArray();
String unicodeBytes = "";
for (int byteIndex = 0; byteIndex < utfBytes.length; byteIndex++) {
String hexB = Integer.toHexString(utfBytes[byteIndex]);
if (hexB.length() <= 2) {
hexB = "00" + hexB;
}
unicodeBytes = unicodeBytes + "\\u" + hexB;
}
System.out.println("unicodeBytes is: " + unicodeBytes);
return unicodeBytes;
}

/**
* This method will decode the String to a recognized String
* in ui.
* @param dataStr
* @return
*/
public static StringBuffer decodeUnicode(final String dataStr) {
int start = 0;
int end = 0;
final StringBuffer buffer = new StringBuffer();
while (start > -1) {
end = dataStr.indexOf("\\u", start + 2);
String charStr = "";
if (end == -1) {
charStr = dataStr.substring(start + 2, dataStr.length());
} else {
charStr = dataStr.substring(start + 2, end);
}
char letter = (char) Integer.parseInt(charStr, 16); // 16进制parse整形字符串。
buffer.append(new Character(letter).toString());
start = end;
}
return buffer;
}

}


5.日期相关

package com.gootrip.util;

/**
* <p>Title: </p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2007</p>
* <p>Company: </p>
* @author <a href="mailto:royiwu@hotmail.com">advance.wu</a>
* @version 1.0
*/
import java.util.*;
import java.text.*;

public class DateHandler {

public DateHandler() {
}
public static int openDay=5;
private String iDate="";
private int iYear;
private int iMonth;
private int iDay;
//  iDateTime = 2002-01-01 23:23:23
public void setDate(String iDateTime){
this.iDate=iDateTime.substring(0,10);
}
public String getDate(){
return this.iDate;
}
public int getYear(){
iYear=Integer.parseInt(iDate.substring(0,4));
return iYear;
}
public int getMonth(){

15f34
iMonth=Integer.parseInt(iDate.substring(5,7));
return iMonth;
}
public int getDay(){
iDay=Integer.parseInt(iDate.substring(8,10));
return iDay;
}

public static String subDate(String date){
return date.substring(0,10);
}

/**
* 计算是否是季度末
* @param date
* @return
*/
public static boolean isSeason(String date){
int getMonth = Integer.parseInt(date.substring(5,7));
boolean sign = false;
if (getMonth==3)
sign = true;
if (getMonth==6)
sign = true;
if (getMonth==9)
sign = true;
if (getMonth==12)
sign = true;
return sign;
}

/**
* 计算从现在开始几天后的时间
* @param afterDay
* @return
*/
public static String getDateFromNow(int afterDay){
GregorianCalendar calendar = new GregorianCalendar();
Date date = calendar.getTime();

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+afterDay);
date = calendar.getTime();

return df.format(date);
}

/**
* 带格式
* @param afterDay
* @param format_string
* @return
*/
public static String getDateFromNow(int afterDay, String format_string)
{
Calendar calendar = Calendar.getInstance();
Date date = null;

DateFormat df = new SimpleDateFormat(format_string);

calendar.set(Calendar.DATE, calendar.get(Calendar.DATE) + afterDay);
date = calendar.getTime();

return df.format(date);
}

/**
* 得到当前时间,用于文件名,没有特殊字符,使用yyyyMMddHHmmss格式
* @param afterDay
* @return
* by tim
*/
public static String getNowForFileName(int afterDay){
GregorianCalendar calendar = new GregorianCalendar();
//    Date date = calendar.getTime();

SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");

calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+afterDay);
Date date = calendar.getTime();

return df.format(date);
}

//==============================================================================
//比较日期,与现在-N天的日期对比  -1 0 1
//==============================================================================
public int getDateCompare(String limitDate,int afterDay){
GregorianCalendar calendar = new GregorianCalendar();
Date date = calendar.getTime();
calendar.set(Calendar.DATE,calendar.get(Calendar.DATE)+afterDay);
date = calendar.getTime();//date是新来的天数,跟今天相比的天数

iDate=limitDate;
calendar.set(getYear(),getMonth()-1,getDay());
Date dateLimit = calendar.getTime();
return dateLimit.compareTo(date);
}
//==============================================================================
//比较日期,与现在的日期对比
//==============================================================================
public int getDateCompare(String limitDate){
iDate=limitDate;
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(getYear(),getMonth()-1,getDay());
Date date = calendar.getTime();

SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date nowDate = new Date();
return date.compareTo(nowDate);
}
//==============================================================================
//比较日期,与现在的日期对比  得到天数
//==============================================================================
public long getLongCompare(String limitDate){

iDate=limitDate;
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(getYear(),getMonth()-1,getDay());
Date date = calendar.getTime();
long datePP=date.getTime();
Date nowDate = new Date();
long dateNow = nowDate.getTime();
return ((dateNow-datePP)/(24*60*60*1000));

}
//==============================================================================
//比较日期,与现在的日期对比  得到信息
//==============================================================================
public String getStringCompare(String limitDate,int openDay){
iDate=limitDate;
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(getYear(),getMonth()-1,getDay());
Date date = calendar.getTime();
long datePP=date.getTime();
Date nowDate = new Date();
long dateNow = nowDate.getTime();
long overDay = ((dateNow-datePP)/(24*60*60*1000));
String info="";
return info;

}
//==============================================================================
//比较日期,与现在的日期对比  得到信息
//==============================================================================
public String getPicCompare(String limitDate,int openDay){

iDate=limitDate;
GregorianCalendar calendar = new GregorianCalendar();
calendar.set(getYear(),getMonth()-1,getDay());
Date date = calendar.getTime();
long datePP=date.getTime();
Date nowDate = new Date();
long dateNow = nowDate.getTime();
long overDay = ((dateNow-datePP)/(24*60*60*1000));
String info="";
if (overDay>0){
info="plaint1.gif";
}
if (overDay==0){
info="plaint2.gif";
}
if (overDay<0&&overDay>=-openDay){
info="plaint2.gif";
}
if (overDay<-openDay){
info="plaint3.gif";
}
if (overDay<-150){
info="plaint3.gif";
}
return info;

}
/**
* method diffdate 计算两个日期间相隔的日子
* @param beforDate 格式:2005-06-20
* @param afterDate 格式:2005-06-21
* @return
*/
public static int diffDate(String beforeDate,String afterDate){
String[] tt = beforeDate.split("-");
Date firstDate = new Date(Integer.parseInt(tt[0]),Integer.parseInt(tt[1])-1,Integer.parseInt(tt[2]));

tt = afterDate.split("-");
Date nextDate = new Date(Integer.parseInt(tt[0]),Integer.parseInt(tt[1])-1,Integer.parseInt(tt[2]));
return (int)(nextDate.getTime()-firstDate.getTime())/(24*60*60*1000);
}

/**
* 获取今天的日期的字符串
* @return
*/
public static String getToday(){
Calendar cld=Calendar.getInstance();
java.util.Date date=new Date();
cld.setTime(date);
int intMon=cld.get(Calendar.MONTH)+1;
int intDay=cld.get(Calendar.DAY_OF_MONTH);
String mons=String.valueOf(intMon);
String days=String.valueOf(intDay);
if(intMon<10)
mons="0"+String.valueOf(intMon);
if(intDay<10)
days="0"+String.valueOf(intDay);
return String.valueOf(cld.get(Calendar.YEAR))+"-"+mons+"-"+days;
}

/**
* 获取当前月份
* @return 返回字符串 格式:两位数
*/
public static String getCurrentMonth(){
String strmonth = null;
Calendar cld = Calendar.getInstance();
java.util.Date date = new Date();
cld.setTime(date);
int intMon=cld.get(Calendar.MONTH) + 1;
if(intMon<10)
strmonth = "0" + String.valueOf(intMon);
else
strmonth = String.valueOf(intMon);
date = null;
return strmonth;
}

//  public static String getCurrMonth()
//  {
//    Calendar cld=Calendar.getInstance();
//    java.util.Date date=new Date();
//    cld.setTime(date);
//    int intMon=cld.get(Calendar.MONTH)+1;
//
//    return String.valueOf(intMon).toString();
//  }

/**
* 获取昨天的日期的字符串
*/
public static String getYestoday(){
Calendar cld = Calendar.getInstance();
java.util.Date date = new Date();
cld.setTime(date);
cld.add(Calendar.DATE,-1);
int intMon = cld.get(Calendar.MONTH)+1;
int intDay = cld.get(Calendar.DAY_OF_MONTH);
String mons = String.valueOf(intMon);
String days = String.valueOf(intDay);
if(intMon < 10)
mons="0" + String.valueOf(intMon);
if(intDay < 10)
days = "0" + String.valueOf(intDay);
return String.valueOf(cld.get(Calendar.YEAR)) + "-" + mons + "-" + days;
}

/**
* 此函数用来计算员工的工作天数,如在使用期和离职期该月份的工作日
* 输入(离职日期,-1)可得该月工作天数  时间以2002-12-14为准
* 输入(入司时间,1)可的该月工作天数
*/
public static int getWorkDay(String date , int sign){
int month=0;
int week=0;
int workDay=0;
Calendar rightNow = Calendar.getInstance();

DateHandler dateOver=new DateHandler();
dateOver.setDate(date);

rightNow.set(rightNow.YEAR,dateOver.getYear());
rightNow.set(rightNow.MONTH,dateOver.getMonth()-1);
rightNow.set(rightNow.DATE,dateOver.getDay());

month = rightNow.get(rightNow.MONTH);

while(rightNow.get(rightNow.MONTH)==month){
week=rightNow.get(Calendar.DAY_OF_WEEK);
if (week==1||week==7){
}else{
workDay++;
System.out.println(rightNow.get(rightNow.DATE));
}
rightNow.add(rightNow.DATE,sign);
}
return workDay;
}

public static void main(String args[]){
System.out.println(DateHandler.isSeason("2002-03-02"));
//    String cc ="100.123.342";
//    System.out.println(cc.indexOf(".",3));
//
//    StringTokenizer st=new StringTokenizer(cc,".");
//
//    if (st.countTokens()!=2) {
//
//    String state = st.nextToken();
//    String event = st.nextToken();
//    System.out.println(""+event);
String strDate = DateHandler.getDateFromNow(0,"yyyy-MM-dd HH:mm:ss");
System.out.println("date:" + strDate);
System.out.println("15:" + strDate.substring(0,16));

Date firstDate = new Date(2006,11,14,18,3,0);
Date nextDate = new Date(2006,11,15,18,2,0);
System.out.println("date's num: " + (int)(nextDate.getTime()-firstDate.getTime())/(24*60*60*1000));
//    }
//System.out.println(DateHandler.getWorkDay("2002-11-14",-1));
}
}


6.时间和日期的工具类

package com.gootrip.util;

/**
* <p>Title: 时间和日期的工具类</p>
* <p>Description: DateUtil类包含了标准的时间和日期格式,以及这些格式在字符串及日期之间转换的方法</p>
* <p>Copyright: Copyright (c) 2007 advance,Inc. All Rights Reserved</p>
* <p>Company: advance,Inc.</p>
* @author advance
* @version 1.0
*/
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;

public class DateUtil {
//~ Static fields/initializers =============================================

private static String datePattern = "MM/dd/yyyy";

private static String timePattern = datePattern + " HH:MM a";

//~ Methods ================================================================

/**
* Return default datePattern (MM/dd/yyyy)
* @return a string representing the date pattern on the UI
*/
public static String getDatePattern() {
return datePattern;
}

/**
* This method attempts to convert an Oracle-formatted date
* in the form dd-MMM-yyyy to mm/dd/yyyy.
*
* @param aDate date from database as a string
* @return formatted string for the ui
*/
public static final String getDate(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate != null) {
df = new SimpleDateFormat(datePattern);
returnValue = df.format(aDate);
}

return (returnValue);
}

public static final String date2Str(Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate != null) {
df = new SimpleDateFormat(datePattern);
returnValue = df.format(aDate);
}

return (returnValue);
}

public static final String date2Str(String pattern, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate != null) {
df = new SimpleDateFormat(pattern);
returnValue = df.format(aDate);
}
return (returnValue);
}

/**
* This method generates a string representation of a date/time
* in the format you specify on input
*
* @param aMask the date pattern the string is in
* @param strDate a string representation of a date
* @return a converted Date object
* @see java.text.SimpleDateFormat
* @throws ParseException
*/
public static final Date convertStringToDate(String aMask, String strDate)
throws ParseException {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(aMask);

try {
date = df.parse(strDate);
} catch (ParseException pe) {
return null;
}

return (date);
}

public static final Date str2Date(String aMask, String strDate)
throws ParseException {
SimpleDateFormat df = null;
Date date = null;
df = new SimpleDateFormat(aMask);

try {
date = df.parse(strDate);
} catch (ParseException pe) {
return null;
}

return (date);
}

/**
* This method returns the current date time in the format:
* MM/dd/yyyy HH:MM a
*
* @param theTime the current time
* @return the current date/time
*/
public static String getTimeNow(Date theTime) {
return getDateTime(timePattern, theTime);
}

/**
* This method returns the current date in the format: MM/dd/yyyy
*
* @return the current date
* @throws ParseException
*/
public static Calendar getToday() throws ParseException {
Date today = new Date();
SimpleDateFormat df = new SimpleDateFormat(datePattern);

// This seems like quite a hack (date -> string -> date),
// but it works ;-)
String todayAsString = df.format(today);
Calendar cal = new GregorianCalendar();
cal.setTime(convertStringToDate(todayAsString));

return cal;
}

/**
* This method generates a string representation of a date's date/time
* in the format you specify on input
*
* @param aMask the date pattern the string is in
* @param aDate a date object
* @return a formatted string representation of the date
*
* @see java.text.SimpleDateFormat
*/
public static final String getDateTime(String aMask, Date aDate) {
SimpleDateFormat df = null;
String returnValue = "";

if (aDate == null) {
System.out.print("aDate is null!");
} else {
df = new SimpleDateFormat(aMask);
returnValue = df.format(aDate);
}

return (returnValue);
}

/**
* This method generates a string representation of a date based
* on the System Property 'dateFormat'
* in the format you specify on input
*
* @param aDate A date to convert
* @return a string representation of the date
*/
public static final String convertDateToString(Date aDate) {
return getDateTime(datePattern, aDate);
}

/**
* This method converts a String to a date using the datePattern
*
* @param strDate the date to convert (in format MM/dd/yyyy)
* @return a date object
*
* @throws ParseException
*/
public static Date convertStringToDate(String strDate)
throws ParseException {
Date aDate = null;

try {

aDate = convertStringToDate(datePattern, strDate);
} catch (ParseException pe) {
//log.error("Could not convert '" + strDate
//          + "' to a date, throwing exception");
pe.printStackTrace();
return null;

}
return aDate;
}

//日期格式转换成时间戳
public static long getTimeStamp(String pattern, String strDate) {
long returnTimeStamp = 0;
Date aDate = null;
try {
aDate = convertStringToDate(pattern, strDate);
} catch (ParseException pe) {
aDate = null;
}
if (aDate == null) {
returnTimeStamp = 0;
} else {
returnTimeStamp = aDate.getTime();
}
return returnTimeStamp;
}

//获取当前日期的邮戳
public static long getNowTimeStamp() {
long returnTimeStamp = 0;
Date aDate = null;
try {
aDate = convertStringToDate("yyyy-MM-dd HH:mm:ss", getNowDateTime());
} catch (ParseException pe) {
aDate = null;
}
if (aDate == null) {
returnTimeStamp = 0;
} else {
returnTimeStamp = aDate.getTime();
}
return returnTimeStamp;
}

/**
*得到格式化后的系统当前日期
*@param strScheme 格式模式字符串
*@return 格式化后的系统当前时间,如果有异常产生,返回空串""
*@see java.util.SimpleDateFormat
*/
public static final String getNowDateTime(String strScheme) {
String strReturn = null;
Date now = new Date();
try {
SimpleDateFormat sdf = new SimpleDateFormat(strScheme);
strReturn = sdf.format(now);
} catch (Exception e) {
strReturn = "";
}
return strReturn;
}

public static final String getNowDateTime() {
String strReturn = null;
Date now = new Date();
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strReturn = sdf.format(now);
} catch (Exception e) {
strReturn = "";
}
return strReturn;
}

/**
*转化日期格式"MM/dd/YY、MM.dd.YY、MM-dd-YY、MM/dd/YY",并输出为正常的格式yyyy-MM-dd
*@param strDate 待转换的日期格式
*@return 格式化后的日期,如果有异常产生,返回空串""
*@see java.util.SimpleDateFormat
*/
public static final String convertNormalDate(String strDate) {
String strReturn = null;
//先把传入参数分格符转换成java认识的分格符
String[] date_arr = strDate.split("\\.|\\/|\\-");
try {
if (date_arr.length == 3) {
if (date_arr[2].length() != 4) {
String nowYear = getNowDateTime("yyyy");
date_arr[2] = nowYear.substring(0, 2) + date_arr[2];
}
strReturn = DateUtil.getDateTime("yyyy-MM-dd",
convertStringToDate(combineStringArray(date_arr, "/")));
}

} catch (Exception e) {
return strReturn;
}
return strReturn;
}

/**
* 将字符串数组使用指定的分隔符合并成一个字符串。
* @param array 字符串数组
* @param delim 分隔符,为null的时候使用""作为分隔符(即没有分隔符)
* @return 合并后的字符串
* @since  0.4
*/
public static final String combineStringArray(String[] array, String delim) {
int length = array.length - 1;
if (delim == null) {
delim = "";
}
StringBuffer result = new StringBuffer(length * 8);
for (int i = 0; i < length; i++) {
result.append(array[i]);
result.append(delim);
}
result.append(array[length]);
return result.toString();
}

public static final int getWeekNum(String strWeek) {
int returnValue = 0;
if (strWeek.equals("Mon")) {
returnValue = 1;
} else if (strWeek.equals("Tue")) {
returnValue = 2;
} else if (strWeek.equals("Wed")) {
returnValue = 3;
} else if (strWeek.equals("Thu")) {
returnValue = 4;
} else if (strWeek.equals("Fri")) {
returnValue = 5;
} else if (strWeek.equals("Sat")) {
returnValue = 6;
} else if (strWeek.equals("Sun")) {
returnValue = 0;
} else if (strWeek == null) {
returnValue = 0;
}

return returnValue;
}
/**
* 获取日期字符串中的中文时间表示字符串
* @param strDate
* @return
*/
public static final String getSabreTime(String strDate) {
String strReturn = "";
try {

Date d = DateUtil.str2Date("yyyy-MM-dd HH:mm:ss", CTool.replace(
strDate, "T", " "));
strReturn = DateUtil.date2Str("hh:mm aaa", d);

} catch (Exception e) {
return strReturn;
}
return strReturn;
}
/**
* 获取日期字符串中的中文日期表示字符串
* @param strDate
* @return
*/
public static final String getSabreDate(String strDate) {
String strReturn = "";
try {
String p = null;
if (strDate.length() > 10)
p = "yyyy-MM-dd HH:mm:ss";
else
p = "yyyy-MM-dd";
Date d = DateUtil.str2Date(p, CTool.replace(strDate, "T", " "));
strReturn = DateUtil.date2Str("EEE d-MMM", d);

} catch (Exception e) {
return strReturn;
}
return strReturn;
}
/**
* 获取日期字符串的中文日期时间表示
* @param strDate
* @return
*/
public static final String getSabreDateTime(String strDate) {
String strReturn = "";
try {
String p = null;
if (strDate.length() > 10)
p = "yyyy-MM-dd HH:mm:ss";
else
p = "yyyy-MM-dd";
Date d = DateUtil.str2Date(p, CTool.replace(strDate, "T", " "));
strReturn = DateUtil.date2Str("EEE d-MMM hh:mm aaa", d);

} catch (Exception e) {
return strReturn;
}
return strReturn;
}

/**
*得到格式化后的指定日期
*@param strScheme 格式模式字符串
*@param date 指定的日期值
*@return 格式化后的指定日期,如果有异常产生,返回空串""
*@see java.util.SimpleDateFormat
*/
public static final String getDateTime(Date date, String strScheme) {
String strReturn = null;
try {
SimpleDateFormat sdf = new SimpleDateFormat(strScheme);
strReturn = sdf.format(date);
} catch (Exception e) {
strReturn = "";
}

return strReturn;
}
/**
* 获取日期
* @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR
* @param timenum  时间数字,譬如:-1 昨天,0 今天,1 明天
* @return 日期
*/
public static final Date getDateFromNow(int timeType, int timenum){
Calendar cld = Calendar.getInstance();
cld.set(timeType, cld.get(timeType) + timenum);
return cld.getTime();
}
/**
* 获取日期
* @param timeType 时间类型,譬如:Calendar.DAY_OF_YEAR
* @param timenum  时间数字,譬如:-1 昨天,0 今天,1 明天
* @param format_string 时间格式,譬如:"yyyy-MM-dd HH:mm:ss"
* @return 字符串
*/
public static final String getDateFromNow(int timeType, int timenum, String format_string){
if ((format_string == null)||(format_string.equals("")))
format_string = "yyyy-MM-dd HH:mm:ss";
Calendar cld = Calendar.getInstance();
Date date = null;
DateFormat df = new SimpleDateFormat(format_string);
cld.set(timeType, cld.get(timeType) + timenum);


7.

/**
*
*/
package com.gootrip.util;

import java.text.NumberFormat;
import java.util.Date;
import java.util.Locale;
import java.util.StringTokenizer;

/**
* @author advance
*
*/
public class DealString {

public DealString() {
}

//判断字符串是否为空,并删除首尾空格
public static String convertNullCode(String tempSql){
if (tempSql==null) tempSql="";
return tempSql;
}
/**
* 字符串替换操作
* @param originString 原字符串
* @param oldString 被替换字符串
* @param newString 替换字符串
* @return 替换操作后的字符串
*/
public static String replace(String originString,String oldString,String newString){
String getstr = originString;
while(getstr.indexOf(oldString)>-1){
getstr = getstr.substring(0,getstr.indexOf(oldString)) + newString + getstr.substring(getstr.indexOf(oldString)+oldString.length(),getstr.length());
}
return getstr;
}
/**
* 代码转换,GBK转换为ISO-8859-1
* @param tempSql 要转换的字符串
* @return
*/
public static String ISOCode(String tempSql){

String returnString = convertNullCode(tempSql);

try{
byte[] ascii = returnString.getBytes("GBK");
returnString = new String(ascii,"ISO-8859-1");
}catch(Exception e){
e.printStackTrace();
}
return returnString;
}

/**
* 代码转换,ISO-8859-1转换为GBK
* @param tempSql 要转换的字符串
* @return
*/
public static String GBKCode(String tempSql){
String returnString = convertNullCode(tempSql);
try{
byte[] ascii = returnString.getBytes("ISO-8859-1");
returnString = new String(ascii,"GBK");
}catch(Exception e){
e.printStackTrace();
}
return returnString;
}
/**
* 代码转换 从srcCode转换为destCode
* @param srcCode 原编码
* @param destCode 目标编码
* @param strTmp 要转换的字符串
* @return
*/
public static String convertCode(String srcCode,String destCode,String strTmp){
String returnString = convertNullCode(strTmp);
try{
byte[] ascii=returnString.getBytes(srcCode);
returnString =new String(ascii,destCode);
}catch(Exception e){
e.printStackTrace();
}
return returnString;
}
/**
* 代码转换,GBK转换为big5
* @param tempSql 要转换的字符串
* @return
*/
public static String GBK2BIG5Code(String tempSql){
String returnString = convertNullCode(tempSql);
try{
byte[] ascii=returnString.getBytes("GBK");
returnString =new String(ascii,"big5");
}catch(Exception e){
e.printStackTrace();
}
return returnString;
}
//替换非法字符
public static String convertHtml(String input){
StringBuffer returnString = new StringBuffer(input.length());

char ch = ' ';
for (int i = 0;i<input.length();i++){

ch = input.charAt( i);

if (ch == '<'){
returnString = returnString.append("<");
}else if (ch == '>'){
returnString = returnString.append(">");
}else if (ch == ' '){
returnString = returnString.append(" ");
}else if (ch == '\\'){
returnString = returnString.append("´");
}else{
returnString = returnString.append(ch);
}
}
return returnString.toString();
}

/*
*
*/
private String delSQlString(String sql){
String delSql = "in(";
StringTokenizer Tokenizer = new StringTokenizer(sql,"|");

// 标记本身等于分隔符的特殊情况
delSql += Tokenizer.nextToken().toString();
while (Tokenizer.hasMoreTokens()) {
delSql += Tokenizer.nextToken() + ",";
}
delSql = delSql.substring(0,delSql.length()-1) + ")";
return delSql;
}

/*
* format selectedIDs to sql language
* in (...)
* second of methods bt own idea
*/
private String delNewSQlString(String sql){
return "in (" + sql.replace('|',',') + ")";
}

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();

/**
* This method takes a string which may contain HTML tags (ie, <b>,
* <table>, etc) and converts the '<'' and '>' characters to
* their HTML escape sequences.
*
* @param in the text to be converted.
* @return the input string with the characters '<' and '>' 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();
}

public static String filterString(String allstr)
{
StringBuffer returnString = new StringBuffer(allstr.length());
char ch = ' ';
for (int i = 0; i < allstr.length(); i++)
{
ch = allstr.charAt(i);
String lsTemp = "'";
char lcTemp = lsTemp.charAt(0);
if (ch == lcTemp)
{
returnString.append("''");
}
else
{
returnString.append(ch);
}
}
return returnString.toString();
}
/**
* 数字的金额表达式
* @param num
* @return
*/
public static String convertNumToMoney(int num){
NumberFormat formatc = NumberFormat.getCurrencyInstance(Locale.CHINA);
String strcurr = formatc.format(num);
System.out.println(strcurr);
//num = NumberFormat.getInstance().setParseIntegerOnly(true));
return strcurr;
}

public static void main(String args[]){
DealString.convertNumToMoney(1234566);
}
}


8.解析url xml文档

/**
*
*/
package com.gootrip.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

/**
* @author advance
*
*/
public class Dom4jHelper {
/**
*  解析url xml文档
* @param url
* @return
* @throws DocumentException
*/
public Document parse(URL url) throws DocumentException {
SAXReader reader = new SAXReader();
Document document = reader.read(url);
return document;
}
/**
* 遍历解析文档
* @param document
*/
public void treeWalk(Document document) {
treeWalk( document.getRootElement() );
}
/**
* 遍历解析元素
* @param element
*/
public void treeWalk(Element element) {
for ( int i = 0, size = element.nodeCount(); i < size; i++ ) {
Node node = element.node(i);
if ( node instanceof Element ) {
treeWalk( (Element) node );
}
else {
// 处理....
}
}
}

/**
* 解析文件,获得根元素
* @param xmlPath
* @param encoding
* @return
* @throws Exception
*/
public static Element parse(String xmlPath,String encoding)throws Exception{
//文件是否存在
File file = new File(xmlPath);
if(!file.exists()){
throw new Exception("找不到xml文件:"+xmlPath);
}

//解析
SAXReader reader = new SAXReader(false);
Document doc = reader.read(new FileInputStream(file),encoding);
Element root = doc.getRootElement();
return root;
}

/**
* 保存文档
* @param doc
* @param xmlPath
* @param encoding
* @throws Exception
*/
public static void save(Document doc,String xmlPath,String encoding)throws Exception{
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding(encoding);
XMLWriter writer = new XMLWriter(new OutputStreamWriter(new FileOutputStream(xmlPath),encoding),format);
writer.write(doc);
writer.flush();
writer.close();
}
/**
* 修改xml某节点的值
* @param inputXml 原xml文件
* @param nodes 要修改的节点
* @param attributename 属性名称
* @param value 新值
* @param outXml 输出文件路径及文件名 如果输出文件为null,则默认为原xml文件
*/
public static void modifyDocument(File inputXml, String nodes, String attributename, String value, String outXml) {
try {
SAXReader saxReader = new SAXReader();
Document document = saxReader.read(inputXml);
List list = document.selectNodes(nodes);
Iterator iter = list.iterator();
while (iter.hasNext()) {
Attribute attribute = (Attribute) iter.next();
if (attribute.getName().equals(attributename))
attribute.setValue(value);
}
XMLWriter output;
if (outXml != null){ //指定输出文件
output = new XMLWriter(new FileWriter(new File(outXml)));
}else{ //输出文件为原文件
output = new XMLWriter(new FileWriter(inputXml));
}
output.write(document);
output.close();
}

catch (DocumentException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
System.out.println(e.getMessage());
}
}

/**
* xml转换为字符串
* @param doc
* @param encoding
* @return
* @throws Exception
*/
public static String toString(Document doc,String encoding)throws Exception{
OutputFormat format=OutputFormat.createPrettyPrint();
format.setEncoding(encoding);
ByteArrayOutputStream byteOS=new ByteArrayOutputStream();
XMLWriter writer = new XMLWriter(new OutputStreamWriter(byteOS,encoding),format);
writer.write(doc);
writer.flush();
writer.close();
writer=null;

return byteOS.toString(encoding);
}
/**
* 字符串转换为Document
* @param text
* @return
* @throws DocumentException
*/
public static Document str2Document(String text) throws DocumentException{
Document document = DocumentHelper.parseText(text);
return document;
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub

}

}


9.编码

package com.bjdv.catv.util;

public class Escape {
private final static String[] hex = { "00", "01", "02", "03", "04", "05",
"06", "07", "08", "09", "0A", "0B", "0C", "0D", "0E", "0F", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19", "1A", "1B",
"1C", "1D", "1E", "1F", "20", "21", "22", "23", "24", "25", "26",
"27", "28", "29", "2A", "2B", "2C", "2D", "2E", "2F", "30", "31",
"32", "33", "34", "35", "36", "37", "38", "39", "3A", "3B", "3C",
"3D", "3E", "3F", "40", "41", "42", "43", "44", "45", "46", "47",
"48", "49", "4A", "4B", "4C", "4D", "4E", "4F", "50", "51", "52",
"53", "54", "55", "56", "57", "58", "59", "5A", "5B", "5C", "5D",
"5E", "5F", "60", "61", "62", "63", "64", "65", "66", "67", "68",
"69", "6A", "6B", "6C", "6D", "6E", "6F", "70", "71", "72", "73",
"74", "75", "76", "77", "78", "79", "7A", "7B", "7C", "7D", "7E",
"7F", "80", "81", "82", "83", "84", "85", "86", "87", "88", "89",
"8A", "8B", "8C", "8D", "8E", "8F", "90", "91", "92", "93", "94",
"95", "96", "97", "98", "99", "9A", "9B", "9C", "9D", "9E", "9F",
"A0", "A1", "A2", "A3", "A4", "A5", "A6", "A7", "A8", "A9", "AA",
"AB", "AC", "AD", "AE", "AF", "B0", "B1", "B2", "B3", "B4", "B5",
"B6", "B7", "B8", "B9", "BA", "BB", "BC", "BD", "BE", "BF", "C0",
"C1", "C2", "C3", "C4", "C5", "C6", "C7", "C8", "C9", "CA", "CB",
"CC", "CD", "CE", "CF", "D0", "D1", "D2", "D3", "D4", "D5", "D6",
"D7", "D8", "D9", "DA", "DB", "DC", "DD", "DE", "DF", "E0", "E1",
"E2", "E3", "E4", "E5", "E6", "E7", "E8", "E9", "EA", "EB", "EC",
"ED", "EE", "EF", "F0", "F1", "F2", "F3", "F4", "F5", "F6", "F7",
"F8", "F9", "FA", "FB", "FC", "FD", "FE", "FF" };

private final static byte[] val = { 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x00, 0x01,
0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F,
0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F, 0x3F };

/** */
/**
* 编码
*
* @param s
* @return
*/
public static String escape(String s) {
StringBuffer sbuf = new StringBuffer();
int len = s.length();
for (int i = 0; i < len; i++) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') {
sbuf.append((char) ch);
} else if ('a' <= ch && ch <= 'z') {
sbuf.append((char) ch);
} else if ('0' <= ch && ch <= '9') {
sbuf.append((char) ch);
} else if (ch == '-' || ch == '_' || ch == '.' || ch == '!'
|| ch == '~' || ch == '*' || ch == '\'' || ch == '('
|| ch == ')') {
sbuf.append((char) ch);
} else if (ch <= 0x007F) {
sbuf.append('%');
sbuf.append(hex[ch]);
} else {
sbuf.append('%');
sbuf.append('u');
sbuf.append(hex[(ch >>> 8)]);
sbuf.append(hex[(0x00FF & ch)]);
}
}
return sbuf.toString();
}

/** */
/**
* 解码 说明:本方法保证 不论参数s是否经过escape()编码,均能得到正确的“解码”结果
*
* @param s
* @return
*/
public static String unescape(String s) {
StringBuffer sbuf = new StringBuffer();
int i = 0;
int len = s.length();
while (i < len) {
int ch = s.charAt(i);
if ('A' <= ch && ch <= 'Z') {
sbuf.append((char) ch);
} else if ('a' <= ch && ch <= 'z') {
sbuf.append((char) ch);
} else if ('0' <= ch && ch <= '9') {
sbuf.append((char) ch);
} else if (ch == '-' || ch == '_' || ch == '.' || ch == '!'
|| ch == '~' || ch == '*' || ch == '\'' || ch == '('
|| ch == ')') {
sbuf.append((char) ch);
} else if (ch == '%') {
int cint = 0;
if ('u' != s.charAt(i + 1)) {
cint = (cint << 4) | val[s.charAt(i + 1)];
cint = (cint << 4) | val[s.charAt(i + 2)];
i += 2;
} else {
cint = (cint << 4) | val[s.charAt(i + 2)];
cint = (cint << 4) | val[s.charAt(i + 3)];
cint = (cint << 4) | val[s.charAt(i + 4)];
cint = (cint << 4) | val[s.charAt(i + 5)];
i += 5;
}
sbuf.append((char) cint);
} else {
sbuf.append((char) ch);
}
i++;
}
return sbuf.toString();
}

public static void main(String[] args) {
String stest = "一声笑傲江湖之曲1234 abcd[]()<+>,.~\"";
System.out.println(stest);
System.out.println(escape(stest));
System.out.println(unescape(escape(stest)));
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: