1.字段验证工具类
对字段进行判断的工具,每个项目必备吧,简单总结了一下,有优化的,或者更多的请提出,可以不断完善。
- import java.util.regex.Matcher;
- import java.util.regex.Pattern;
- /**
- * 字段验证工具
- * @author lixinglei
- *
- */
- public class ValidatorUtil {
- /**
- * 判断是否为浮点数或者整数
- * @param str
- * @return true Or false
- */
- public static boolean isNumeric(String str){
- Pattern pattern = Pattern.compile("^(-?\\d+)(\\.\\d+)?$");
- Matcher isNum = pattern.matcher(str);
- if( !isNum.matches() ){
- return false;
- }
- return true;
- }
- /**
- * 判断是否为正确的邮件格式
- * @param str
- * @return boolean
- */
- public static boolean isEmail(String str){
- if(isEmpty(str))
- return false;
- return str.matches("^[\\w-]+(\\.[\\w-]+)*@[\\w-]+(\\.[\\w-]+)+$");
- }
- /**
- * 判断字符串是否为合法手机号 11位 13 14 15 18开头
- * @param str
- * @return boolean
- */
- public static boolean isMobile(String str){
- if(isEmpty(str))
- return false;
- return str.matches("^(13|14|15|18)\\d{9}$");
- }
- /**
- * 判断是否为数字
- * @param str
- * @return
- */
- public static boolean isNumber(String str) {
- try{
- Integer.parseInt(str);
- return true;
- }catch(Exception ex){
- return false;
- }
- }
- /**
- * 判断字符串是否为非空(包含null与"")
- * @param str
- * @return
- */
- public static boolean isNotEmpty(String str){
- if(str == null || "".equals(str))
- return false;
- return true;
- }
- /**
- * 判断字符串是否为非空(包含null与""," ")
- * @param str
- * @return
- */
- public static boolean isNotEmptyIgnoreBlank(String str){
- if(str == null || "".equals(str) || "".equals(str.trim()))
- return false;
- return true;
- }
- /**
- * 判断字符串是否为空(包含null与"")
- * @param str
- * @return
- */
- public static boolean isEmpty(String str){
- if(str == null || "".equals(str))
- return true;
- return false;
- }
- /**
- * 判断字符串是否为空(包含null与""," ")
- * @param str
- * @return
- */
- public static boolean isEmptyIgnoreBlank(String str){
- if(str == null || "".equals(str) || "".equals(str.trim()))
- return true;
- return false;
- }
- //禁止实例化
- private ValidatorUtil(){}
- }
2.人民币大写金额转换
在项目开发过程中偶尔会遇到需要把人民币金额由数字转换成大写金额的形式,例如,将“123456”转换成“壹拾贰万叁千肆百伍拾陆”这样子,这种情况在程序需要打印一些单据时会普遍用到,而下面一个程序就解决了这个问题,如果大家觉得有用,请一定帮我顶起来啊^-^,另外,希望各网友也将自己的类似的处理程序拿出来分享。
- import java.text.DecimalFormat;
- import java.text.NumberFormat;
- //总体思路:
- //对数字进行分级处理,级长为4
- //对分级后的每级分别处理,处理后得到字符串相连
- //如:123456=12|3456
- //第二级:12=壹拾贰 + “万”
- //第一级:3456 =叁千肆百伍拾陆 + “”
- public final class RMB {
- private double amount = 0.0D;
- private static final String NUM = "零壹贰叁肆伍陆柒捌玖";
- private static final String UNIT = "仟佰拾个";
- private static final String GRADEUNIT = "仟万亿兆";
- private static final String DOTUNIT = "角分厘";
- private static final int GRADE = 4;
- private static final String SIGN = "¥";
- private static final NumberFormat nf = new DecimalFormat("#0.###");
- public RMB(double amount) {
- this.amount = amount;
- }
- public String toBigAmt(){
- return toBigAmt(this.amount);
- }
- public static String toBigAmt(double amount){
- String amt = nf.format(amount);
- Double d = new Double(amount);
- String dotPart = ""; //取小数位
- String intPart = ""; //取整数位
- int dotPos;
- if ( (dotPos = amt.indexOf('.')) != -1) {
- intPart = amt.substring(0, dotPos);
- dotPart = amt.substring(dotPos + 1);
- }
- else {
- intPart = amt;
- }
- if(intPart.length() > 16) throw new java.lang.InternalError("The amount is too big.");
- String intBig = intToBig(intPart);
- String dotBig = dotToBig(dotPart);
- //以下代码稍做修改,现在是完美的代码啦!
- if ((dotBig.length() == 0)&&(intBig.length() != 0)) {
- return intBig + "元整";
- }else if((dotBig.length() == 0)&&(intBig.length() == 0)){
- return intBig + "零元";
- }else if((dotBig.length() != 0)&&(intBig.length() != 0)) {
- return intBig + "元" + dotBig;
- }else{
- return dotBig;
- }
- /*
- if(dotBig.length() == 0) return intBig +"元整";
- else return intBig + "元" + dotBig;
- */
- }
- private static String dotToBig(String dotPart){
- //得到转换后的大写(小数部分)
- String strRet = "";
- for(int i=0; i<dotPart.length() && i<3; i++){
- int num;
- if((num = Integer.parseInt(dotPart.substring(i,i+1))) != 0)
- strRet += NUM.substring(num,num+1) + DOTUNIT.substring(i,i+1);
- }
- return strRet;
- }
- private static String intToBig(String intPart){
- //得到转换后的大写(整数部分)
- int grade; //级长
- String result = "";
- String strTmp = "";
- //得到当级长
- grade = intPart.length() / GRADE;
- //调整级次长度
- if(intPart.length() % GRADE != 0) grade += 1;
- //对每级数字处理
- for(int i = grade; i >= 1; i--){
- strTmp = getNowGradeVal(intPart, i);//取得当前级次数字
- result += getSubUnit(strTmp);//转换大写
- result = dropZero(result);//除零
- //加级次单位
- if( i>1 ) //末位不加单位
- //单位不能相连续
- if(getSubUnit(strTmp).equals("零零零零")){
- result += "零"+GRADEUNIT.substring(i - 1, i);
- }else{
- result += GRADEUNIT.substring(i - 1, i);
- }
- }
- return result;
- }
- private static String getNowGradeVal(String strVal,int grade){
- //得到当前级次的串
- String rst;
- if(strVal.length() <= grade * GRADE)
- rst = strVal.substring(0,strVal.length() - (grade-1)*GRADE);
- else
- rst = strVal.substring(strVal.length() - grade*GRADE,strVal.length() - (grade-1)*GRADE);
- return rst;
- }
- private static String getSubUnit(String strVal){
- //数值转换
- String rst = "";
- for(int i = 0;i< strVal.length(); i++){
- String s = strVal.substring(i,i+1);
- int num = Integer.parseInt(s);
- if(num == 0){
- //“零”作特殊处理
- if(i != strVal.length()) //转换后数末位不能为零
- rst += "零";
- }else{
- //If IntKey = 1 And i = 2 Then
- //“壹拾”作特殊处理
- //“壹拾”合理
- //Else
- rst += NUM.substring(num,num+1);
- //End If
- //追加单位
- if(i != strVal.length()-1 )//个位不加单位
- rst += UNIT.substring(i+4-strVal.length(),i+4-strVal.length()+1);
- }
- }
- return rst;
- }
- private static String dropZero(String strVal){
- //去除连继的“零”
- String strRst;
- String strBefore; //前一位置字符
- String strNow; //现在位置字符
- strBefore = strVal.substring(0,1);
- strRst = strBefore;
- for(int i= 1; i<strVal.length(); i++) {
- strNow = strVal.substring(i, i+1);
- if(strNow.equals("零") && strBefore.equals("零"))
- ;//同时为零
- else
- strRst += strNow;
- strBefore = strNow;
- }
- //末位去零
- if(strRst.substring(strRst.length()-1, strRst.length()).equals("零"))
- strRst = strRst.substring(0,strRst.length()-1);
- return strRst;
- }
- public static void main(String[] args) {
- System.out.println(RMB.toBigAmt(10052345.00D));
- System.out.println(RMB.toBigAmt(0.00D));
- System.out.println(RMB.toBigAmt(0.60D));
- System.out.println(RMB.toBigAmt(00.60D));
- System.out.println(RMB.toBigAmt(150.2101D));
- System.out.println(RMB.toBigAmt(15400089666.234D));
- System.out.println(RMB.toBigAmt(22200004444.2347D));
- }
- }
3.Java获取文件本身所在磁盘位置
们在做java开发(纯java程序,或者java web开发)时,经常会遇到需要读取配置文件的需求,如果我们将文件所在位置的信息直接写到程序中,例如:E:/workspace/JavaGUI/bin/com/util这个目录,这样虽然可行,但是,却产生了很大的局限性,因为读取的文件必须要要满足在E:/workspace/JavaGUI/bin/com/util之下才能够被正常读取,否则java抛异常。那如果在没有E盘盘符的服务器上,这样的程序是没办法执行的。所以就需要我们的程序能够读取当前文件的所在位置,从而确定文件的物理磁盘位置,而不是手动写入这个位置。
以下程序,就实现了这个功能
- /**
- * 得到类的路径,例如E:/workspace/JavaGUI/bin/com/util
- * @return
- * @throws java.lang.Exception
- */
- public String getClassPath() throws Exception {
- try {
- String strClassName = getClass().getName();
- String strPackageName = "";
- if (getClass().getPackage() != null) {
- strPackageName = getClass().getPackage().getName();
- }
- String strClassFileName = "";
- if (!"".equals(strPackageName)) {
- strClassFileName = strClassName.substring(strPackageName.length() + 1,
- strClassName.length());
- } else {
- strClassFileName = strClassName;
- }
- URL url = null;
- url = getClass().getResource(strClassFileName + ".class");
- String strURL = url.toString();
- strURL = strURL.substring(strURL.indexOf('/') + 1, strURL
- .lastIndexOf('/'));
- //返回当前类的路径,并且处理路径中的空格,因为在路径中出现的空格如果不处理的话,
- //在访问时就会从空格处断开,那么也就取不到完整的信息了,这个问题在web开发中尤其要注意
- return strURL.replaceAll("%20", " ");
- } catch (Exception ex) {
- ex.printStackTrace();
- throw ex;
- }
- }
4.Java中数据处理工具类
在开发java项目时,经常都需要频繁处理数据,如果能非常合适、严谨的处理数据,那么将对程序有莫大的好处,例如,提高程序的稳定性,而且有时候数据在使用前是必须处理的,否则就会出错。例如,在操作前对被除数的处理(如果是0怎么办)、字符串转化、编码转换等,针对项目开发中对数据的频繁操作,在我们程序的开发过程中是很有必要对这些处理数据的工具方法进行统一归类使用的,而下面的这个工具类就封装了很多对基础数据的处理操作的方法。因为方法很多,为了方便查询,我先对方法及其实现的功能列了一个清单,如下:
同时也希望大家能把自己使用的工具类发上来共享,谢谢。
一、功能方法目录清单:
1、getString(String sSource)的功能是判断参数是否为空,为空返回"",否则返回其值;
2、getString(int iSource)的功能是判断参数是否为0,为0则返回"",否则返回其值;
3、GBKtoISO(String s)的功能是进行编码转换,由GBK转为 iso-8859-1;
4、ISOtoGBK(String s)的功能是进行编码转换,由iso-8859-1 转为 GBK;
5、getArray(String[] aSource)的功能是判断参数是否为空,为空则返回一个长度为0的字符串数组,否则返回其值;
6、getInt(String sSource)的功能是判断参数是否为空,为空则返回0,不为空则返回其整型值;
7、getIntArray(String[] aSource)的功能是判断参数是否为空,为空则返回一个长度为0的整形数组,否则返回其值;
8、getDouble(String sSource)的功能是判断参数是否为空,为空则返回0,不为空则返回其整型值;
9、isContain(String sSource, String sItem)的功能是查找以逗号分隔的源字符串是否包含给定字符串;
10、isContain(String[] aSource, String sItem)的功能是查找源字符串数组中是否包含给定字符串;
11、delete(String source, String subString)的功能是将指定字符串从源字符串中删除掉,并返回替换后的结果字符串;
12、replace(String source, String oldString, String newString)的功能是用新字符串替换源字符串中的旧字符串;
13、increaseOne(String sSource)的功能是将给定的源字符串加1 例如:“0001” 经本函数转换后返回为“0002”;
14、intToStr(int val, int len)的功能是将给定的整数转化成字符串,结果字符串的长度为给定长度,不足位数的左端补"0";
15、arrayAddSign(String[] aSource, String sChar)的功能是将数组中的每个元素两端加上给定的符号;
16、arrayToString(String[] aSource)的功能是将数组中的元素连成一个以逗号分隔的字符串;
17、arrayToString(int[] aSource)的功能是将数组中的元素连成一个以逗号分隔的字符串;
18、arrayToString(String[] aSource, String sChar)的功能是将数组中的元素连成一个以给定字符分隔的字符串;
19、arrayAppend(String[] array1, String[] array2)的功能是将两个字符串的所有元素连结为一个字符串数组;
20、arrayAppend(Object[] array1, Object[] array2)的功能是将两个对象数组中的所有元素连结为一个对象数组;
21、strToArray(String sSource)的功能是拆分以逗号分隔的字符串,并存入String数组中;
22、strToArray(String sSource, String sChar)的功能是拆分以给定分隔符分隔的字符串,并存入字符串数组中;
23、strToArray(String sSource, char sChar)的功能是拆分以给定分隔符分隔的字符串,并存入整型数组中;
24、addMark(String sSource)的功能是将以逗号分隔的字符串的每个元素加上单引号 如: 1000,1001,1002 --> '1000','1001','1002';
25、deleteFile(String fileName)的功能是删除磁盘上的文件;
26、isNumber(String strInput)的功能是判断字符串是否可转换成数字;
27、isIp(String strIp)的功能是判断输入的字符是否是IP地址的形式;
- import java.io.File;
- import java.io.Serializable;
- import java.math.BigDecimal;
- import java.util.Hashtable;
- import java.util.Set;
- import java.util.StringTokenizer;
- import java.util.Vector;
- /*******************************************************************************
- * 文件名称:Function.java<br>
- * 功能描述:工具类,封装一些常用的操作<br>
- ******************************************************************************/
- public class Function implements Serializable {
- private static final long serialVersionUID = 1L;
- public Function() {
- }
- public static void main(String args[]) {
- }
- /**
- * 判断参数是否为空,为空则返回"",否则返回其值
- * @param sSource 源字符串
- * @return 字符串
- */
- public String getString(String sSource) {
- String sReturn = "";
- if (sSource != null) {
- sReturn = sSource;
- }
- return sReturn;
- }
- /**
- * 判断参数是否为0,为0则返回"",否则返回其值
- * @param iSource 源字符串
- * @return 字符串
- */
- public static String getString(int iSource) {
- if (iSource == 0) {
- return "";
- } else {
- return "" + iSource;
- }
- }
- /**
- * 转码:GBK ----> iso-8859-1
- * @param s 转码字段
- * @return 转码后的字段
- */
- public static String GBKtoISO(String s) {
- try {
- s = new String(s.getBytes("GBK"), "iso-8859-1");
- } catch (Exception e) {
- }
- return s;
- }
- /**
- * 转码:iso-8859-1 ----> GBK
- * @param s 转码字段
- * @return 转码后的字段
- */
- public static String ISOtoGBK(String s) {
- try {
- s = new String(s.getBytes("iso-8859-1"), "GBK");
- } catch (Exception e) {
- }
- return s;
- }
- /**
- * 判断参数是否为空,为空则返回一个长度为0的字符串数组,否则返回其值
- * @param aSource 源字符串数组
- * @return 字符串
- */
- public String[] getArray(String[] aSource) {
- String aReturn[] = new String[0];
- if (aSource != null) {
- aReturn = aSource;
- }
- return aReturn;
- }
- /**
- * 判断参数是否为空,为空则返回0,不为空则返回其整型值
- * @param sSource 源字符串
- * @return 整型数
- */
- public int getInt(String sSource) {
- int iReturn = 0;
- if (sSource != null && !sSource.equals("")) {
- iReturn = Integer.parseInt(sSource);
- }
- return iReturn;
- }
- /**
- * 判断参数是否为空,为空则返回一个长度为0的整形数组,否则返回其值
- * @param aSource 源字符串数组
- * @return 整形数组
- */
- public int[] getIntArray(String[] aSource) {
- int iReturn[] = new int[0];
- if (aSource != null) {
- iReturn = new int[aSource.length];
- for (int i = 0; i < aSource.length; i++) {
- iReturn[i] = Integer.parseInt(aSource[i]);
- }
- }
- return iReturn;
- }
- /**
- * 判断参数是否为空,为空则返回0,不为空则返回其整型值
- * @param sSource 源字符串
- * @return Double数
- */
- public double getDouble(String sSource) {
- double dReturn = 0.00;
- if (sSource != null && !sSource.equals("")) {
- dReturn = (new Double(sSource)).doubleValue();
- }
- return dReturn;
- }
- /**
- * 查找以逗号分隔的源字符串是否包含给定字符串
- * @param sSource :源字符串
- * @param sItem :子串
- * @return 是否包含
- */
- public boolean isContain(String sSource, String sItem) {
- boolean isReturn = false;
- StringTokenizer st = null;
- st = new StringTokenizer(sSource, ",");
- while (st.hasMoreTokens()) {
- if (sItem.equals(st.nextToken())) {
- isReturn = true;
- break;
- }
- }
- return isReturn;
- }
- /**
- * 查找源字符串数组中是否包含给定字符串
- * @param aSource :源字符串数组
- * @param sItem :子串
- * @return 是否包含
- */
- public boolean isContain(String[] aSource, String sItem) {
- boolean isReturn = false;
- for (int i = 0; i < aSource.length; i++) {
- if (sItem.equals(aSource[i])) {
- isReturn = true;
- break;
- }
- }
- return isReturn;
- }
- /**
- * 将指定字符串从源字符串中删除掉,并返回替换后的结果字符串
- * @param source 源字符串
- * @param subString 要删除的字符
- * @return 替换后的字符串
- */
- public String delete(String source, String subString) {
- StringBuffer output = new StringBuffer();
- //源字符串长度
- int lengthOfSource = source.length();
- //开始搜索位置
- int posStart = 0;
- //搜索到老字符串的位置
- int pos;
- while ((pos = source.indexOf(subString, posStart)) >= 0) {
- output.append(source.substring(posStart, pos));
- posStart = pos + 1;
- }
- if (posStart < lengthOfSource) {
- output.append(source.substring(posStart));
- }
- return output.toString();
- }
- /**
- * 此函数有三个输入参数,源字符串(将被操作的字符串),原字符串中被替换的字符串(旧字符串)
- * 替换的字符串(新字符串),函数接收源字符串、旧字符串、新字符串三个值后,
- * 用新字符串代替源字符串中的旧字符串并返回结果
- * @param source 源字符串
- * @param oldString 旧字符串
- * @param newString 新字符串
- * @return 替换后的字符串
- */
- public static String replace(String source, String oldString,
- String newString) {
- StringBuffer output = new StringBuffer();
- int lengthOfSource = source.length(); // 源字符串长度
- int lengthOfOld = oldString.length(); // 老字符串长度
- int posStart = 0; // 开始搜索位置
- int pos; // 搜索到老字符串的位置
- while ((pos = source.indexOf(oldString, posStart)) >= 0) {
- output.append(source.substring(posStart, pos));
- output.append(newString);
- posStart = pos + lengthOfOld;
- }
- if (posStart < lengthOfSource) {
- output.append(source.substring(posStart));
- }
- return output.toString();
- }
- /**
- * 将给定的源字符串加1 例如:“0001” 经本函数转换后返回为“0002”
- * @param sSource :源字符串
- * @return 返回字符串
- */
- public String increaseOne(String sSource) {
- String sReturn = null;
- int iSize = 0;
- iSize = sSource.length();
- long l = (new Long(sSource)).longValue();
- l++;
- sReturn = String.valueOf(l);
- for (int i = sReturn.length(); i < iSize; i++) {
- sReturn = "0" + sReturn;
- }
- return sReturn;
- }
- /**
- * 将给定的整数转化成字符串,结果字符串的长度为给定长度,不足位数的左端补"0"
- * 例如val=10,len=5,那么生成的字符串为"00010"
- * @param val 将被转化成字符串的整数
- * @param len 转化后的长度
- * @return String 返回值
- */
- public String intToStr(int val, int len) {
- String sReturn = new String();
- sReturn = String.valueOf(val);
- if (sReturn.length() < len) {
- for (int i = len - sReturn.length(); i > 0; i--) {
- sReturn = "0" + sReturn;
- }
- }
- return sReturn;
- }
- /**
- * 将数组中的每个元素两端加上给定的符号
- * @param aSource 源数组
- * @param sChar 符号
- * @return 处理后的字符串数组
- */
- public String[] arrayAddSign(String[] aSource, String sChar) {
- String aReturn[] = new String[aSource.length];
- for (int i = 0; i < aSource.length; i++) {
- aReturn[i] = sChar + aSource[i] + sChar;
- }
- return aReturn;
- }
- /**
- * 将数组中的元素连成一个以逗号分隔的字符串
- * @param aSource 源数组
- * @return 字符串
- */
- public String arrayToString(String[] aSource) {
- String sReturn = "";
- for (int i = 0; i < aSource.length; i++) {
- if (i > 0) {
- sReturn += ",";
- }
- sReturn += aSource[i];
- }
- return sReturn;
- }
- /**
- * 将数组中的元素连成一个以逗号分隔的字符串
- * @param aSource 源数组
- * @return 字符串
- */
- public String arrayToString(int[] aSource) {
- String sReturn = "";
- for (int i = 0; i < aSource.length; i++) {
- if (i > 0) {
- sReturn += ",";
- }
- sReturn += aSource[i];
- }
- return sReturn;
- }
- /**
- * 将数组中的元素连成一个以给定字符分隔的字符串
- * @param aSource 源数组
- * @param sChar 分隔符
- * @return 字符串
- */
- public String arrayToString(String[] aSource, String sChar) {
- String sReturn = "";
- for (int i = 0; i < aSource.length; i++) {
- if (i > 0) {
- sReturn += sChar;
- }
- sReturn += aSource[i];
- }
- return sReturn;
- }
- /**
- * 将两个字符串的所有元素连结为一个字符串数组
- * @param array1 源字符串数组1
- * @param array2 源字符串数组2
- * @return String[]
- */
- public String[] arrayAppend(String[] array1, String[] array2) {
- int iLen = 0;
- String aReturn[] = null;
- if (array1 == null) {
- array1 = new String[0];
- }
- if (array2 == null) {
- array2 = new String[0];
- }
- iLen = array1.length;
- aReturn = new String[iLen + array2.length];
- /**
- * 将第一个字符串数组的元素加到结果数组中
- */
- for (int i = 0; i < iLen; i++) {
- aReturn[i] = array1[i];
- }
- /**
- * 将第二个字符串数组的元素加到结果数组中
- */
- for (int i = 0; i < array2.length; i++) {
- aReturn[iLen + i] = array2[i];
- }
- return aReturn;
- }
- /**
- * 将两个对象数组中的所有元素连结为一个对象数组
- * @param array1 源字符串数组1
- * @param array2 源字符串数组2
- * @return Object[]
- */
- public Object[] arrayAppend(Object[] array1, Object[] array2) {
- int iLen = 0;
- Object aReturn[] = null;
- if (array1 == null) {
- array1 = new Object[0];
- }
- if (array2 == null) {
- array2 = new Object[0];
- }
- iLen = array1.length;
- aReturn = new Object[iLen + array2.length];
- /**
- * 将第一个对象数组的元素加到结果数组中
- */
- for (int i = 0; i < iLen; i++) {
- aReturn[i] = array1[i];
- }
- /**
- * 将第二个对象数组的元素加到结果数组中
- */
- for (int i = 0; i < array2.length; i++) {
- aReturn[iLen + i] = array2[i];
- }
- return aReturn;
- }
- /**
- * 拆分以逗号分隔的字符串,并存入String数组中
- * @param sSource 源字符串
- * @return String[]
- */
- public String[] strToArray(String sSource) {
- String aReturn[] = null;
- StringTokenizer st = null;
- st = new StringTokenizer(sSource, ",");
- aReturn = new String[st.countTokens()];
- int i = 0;
- while (st.hasMoreTokens()) {
- aReturn[i] = st.nextToken();
- i++;
- }
- return aReturn;
- }
- /**
- * 拆分以给定分隔符分隔的字符串,并存入字符串数组中
- * @param sSource 源字符串
- * @param sChar 分隔符
- * @return String[]
- */
- public static String[] strToArray(String sSource, String sChar) {
- String aReturn[] = null;
- StringTokenizer st = null;
- st = new StringTokenizer(sSource, sChar);
- int i = 0;
- aReturn = new String[st.countTokens()];
- while (st.hasMoreTokens()) {
- aReturn[i] = st.nextToken();
- i++;
- }
- return aReturn;
- }
- /**
- * 拆分以给定分隔符分隔的字符串,并存入整型数组中
- * @param sSource 源字符串
- * @param sChar 分隔符
- * @return int[]
- */
- public static int[] strToArray(String sSource, char sChar) {
- int aReturn[] = null;
- StringTokenizer st = null;
- st = new StringTokenizer(sSource, String.valueOf(sChar));
- int i = 0;
- aReturn = new int[st.countTokens()];
- while (st.hasMoreTokens()) {
- aReturn[i] = Integer.parseInt(st.nextToken());
- i++;
- }
- return aReturn;
- }
- /**
- * 将以逗号分隔的字符串的每个元素加上单引号 如: 1000,1001,1002 --> '1000','1001','1002'
- * @param sSource 源串
- * @return String
- */
- public String addMark(String sSource) {
- String sReturn = "";
- StringTokenizer st = null;
- st = new StringTokenizer(sSource, ",");
- if (st.hasMoreTokens()) {
- sReturn += "'" + st.nextToken() + "'";
- }
- while (st.hasMoreTokens()) {
- sReturn += "," + "'" + st.nextToken() + "'";
- }
- return sReturn;
- }
- /**
- * 删除磁盘上的文件
- * @param fileName 文件全路径
- * @return boolean
- */
- public boolean deleteFile(String fileName) {
- File file = new File(fileName);
- return file.delete();
- }
- /**
- * 判断字符串是否可转换成数字
- * @param fileName 源串
- * @return boolean
- */
- public static boolean isNumber(String strInput){
- boolean bRs=false;
- int nRs=0;
- try{
- nRs=Integer.parseInt(strInput);
- bRs=true;
- }catch(Exception e){
- bRs=false;
- }
- return bRs;
- }
- /**
- * 判断输入的字符是否是IP地址的形式
- * @param fileName 源串
- * @return boolean
- */
- public static boolean isIp(String strIp){
- boolean bRs=false;
- int nCount=0;
- try{
- String strTmp="";
- StringTokenizer st=new StringTokenizer(strIp,".");
- while (st.hasMoreElements()){
- nCount++;
- strTmp=st.nextToken();
- if(isBigger("1",strTmp) || isBigger(strTmp,"255"))
- return false;
- }
- if (nCount==4)
- bRs=true;
- } catch(Exception e){
- bRs=false;
- }
- return bRs;
- }
- }
此类包含的方法已经在实际项目开发中使用通过,这样把平常开发中经常用到的小功能封装到一个公共类里面,即减少了代码量、提高了代码重用率,又可以很方便的查询、使用,统一修改,提高了劳动率,甚至有些结构功能相似的系统间接口小程序都可以直接保留其他接口的功能框架,只改变其中的业务逻辑就可以了,非常方便
5.Java日期处理工具类
public class DateUtil
{
//默认显示日期的格式
public static final String DATAFORMAT_STR = "yyyy-MM-dd";
//默认显示日期的格式
public static final String YYYY_MM_DATAFORMAT_STR = "yyyy-MM";
//默认显示日期时间的格式
public static final String DATATIMEF_STR = "yyyy-MM-dd HH:mm:ss";
//默认显示简体中文日期的格式
public static final String ZHCN_DATAFORMAT_STR = "yyyy年MM月dd日";
//默认显示简体中文日期时间的格式
public static final String ZHCN_DATATIMEF_STR = "yyyy年MM月dd日HH时mm分ss秒";
//默认显示简体中文日期时间的格式
public static final String ZHCN_DATATIMEF_STR_4yMMddHHmm = "yyyy年MM月dd日HH时mm分";
private static DateFormat dateFormat = null;
private static DateFormat dateTimeFormat = null;
private static DateFormat zhcnDateFormat = null;
private static DateFormat zhcnDateTimeFormat = null;
static
{
dateFormat = new SimpleDateFormat(DATAFORMAT_STR);
dateTimeFormat = new SimpleDateFormat(DATATIMEF_STR);
zhcnDateFormat = new SimpleDateFormat(ZHCN_DATAFORMAT_STR);
zhcnDateTimeFormat = new SimpleDateFormat(ZHCN_DATATIMEF_STR);
}
private static DateFormat getDateFormat(String formatStr)
{
if (formatStr.equalsIgnoreCase(DATAFORMAT_STR))
{
return dateFormat;
}
else
if (formatStr.equalsIgnoreCase(DATATIMEF_STR))
{
return dateTimeFormat;
}
else
if (formatStr.equalsIgnoreCase(ZHCN_DATAFORMAT_STR))
{
return zhcnDateFormat;
}
else
if (formatStr.equalsIgnoreCase(ZHCN_DATATIMEF_STR))
{
return zhcnDateTimeFormat;
}
else
{
return new SimpleDateFormat(formatStr);
}
}
/**
* 按照默认显示日期时间的格式"yyyy-MM-dd HH:mm:ss",转化dateTimeStr为Date类型
* dateTimeStr必须是"yyyy-MM-dd HH:mm:ss"的形式
* @param dateTimeStr
* @return
*/
public static Date getDate(String dateTimeStr)
{
return getDate(dateTimeStr, DATATIMEF_STR);
}
/**
* 按照默认formatStr的格式,转化dateTimeStr为Date类型
* dateTimeStr必须是formatStr的形式
* @param dateTimeStr
* @param formatStr
* @return
*/
public static Date getDate(String dateTimeStr, String formatStr)
{
try
{
if (dateTimeStr == null || dateTimeStr.equals(""))
{
return null;
}
DateFormat sdf = getDateFormat(formatStr);
java.util.Date d = sdf.parse(dateTimeStr);
return d;
}
catch (ParseException e)
{
throw new RuntimeException(e);
}
}
/**
* 将YYYYMMDD转换成Date日期
* @param date
* @return
* @throws BusinessException
*/
public static Date transferDate(String date) throws Exception
{
if (date == null || date.length() < 1)
return null;
if (date.length() != 8)
throw new Exception("日期格式错误");
String con = "-";
String yyyy = date.substring(0, 4);
String mm = date.substring(4, 6);
String dd = date.substring(6, 8);
int month = Integer.parseInt(mm);
int day = Integer.parseInt(dd);
if (month < 1 || month > 12 || day < 1 || day > 31)
throw new Exception("日期格式错误");
String str = yyyy + con + mm + con + dd;
return DateUtil.getDate(str, DateUtil.DATAFORMAT_STR);
}
/**
* 将YYYY-MM-DD日期转换成yyyymmdd格式字符串
* @param date
* @return
*/
public static String getYYYYMMDDDate(Date date)
{
if (date == null)
return null;
String yyyy = getYear(date) + "";
String mm = getMonth(date) + "";
String dd = getDay(date) + "";
mm = StringUtil.rightAlign(mm, 2, "0");
dd = StringUtil.rightAlign(dd, 2, "0");
return yyyy + mm + dd;
}
/**
* 将YYYY-MM-DD日期转换成YYYYMMDDHHMMSS格式字符串
* @param date
* @return
*/
public static String getYYYYMMDDHHMMSSDate(Date date)
{
if (date == null)
return null;
String yyyy = getYear(date) + "";
String mm = getMonth(date) + "";
String dd = getDay(date) + "";
String hh = getHour(date) + "";
String min = getMin(date) + "";
String ss = getSecond(date) + "";
mm = StringUtil.rightAlign(mm, 2, "0");
dd = StringUtil.rightAlign(dd, 2, "0");
hh = StringUtil.rightAlign(hh, 2, "0");
min = StringUtil.rightAlign(min, 2, "0");
ss = StringUtil.rightAlign(ss, 2, "0");
return yyyy + mm + dd + hh + min + ss;
}
/**
* 将YYYY-MM-DD日期转换成yyyymmdd格式字符串
* @param date
* @return
*/
public static String getYYYYMMDDDate(String date)
{
return getYYYYMMDDDate(getDate(date, DATAFORMAT_STR));
}
/**
* 将Date转换成字符串“yyyy-mm-dd hh:mm:ss”的字符串
* @param date
* @return
*/
public static String dateToDateString(Date date)
{
return dateToDateString(date, DATATIMEF_STR);
}
/**
* 将Date转换成formatStr格式的字符串
* @param date
* @param formatStr
* @return
*/
public static String dateToDateString(Date date, String formatStr)
{
DateFormat df = getDateFormat(formatStr);
return df.format(date);
}
/**
* 返回一个yyyy-MM-dd HH:mm:ss 形式的日期时间字符串中的HH:mm:ss
* @param dateTime
* @return
*/
public static String getTimeString(String dateTime)
{
return getTimeString(dateTime, DATATIMEF_STR);
}
/**
* 返回一个formatStr格式的日期时间字符串中的HH:mm:ss
* @param dateTime
* @param formatStr
* @return
*/
public static String getTimeString(String dateTime, String formatStr)
{
Date d = getDate(dateTime, formatStr);
String s = dateToDateString(d);
return s.substring(DATATIMEF_STR.indexOf('H'));
}
/**
* 获取当前日期yyyy-MM-dd的形式
* @return
*/
public static String getCurDate()
{
//return dateToDateString(new Date(),DATAFORMAT_STR);
return dateToDateString(Calendar.getInstance().getTime(), DATAFORMAT_STR);
}
/**
* 获取当前日期yyyy年MM月dd日的形式
* @return
*/
public static String getCurZhCNDate()
{
return dateToDateString(new Date(), ZHCN_DATAFORMAT_STR);
}
/**
* 获取当前日期时间yyyy-MM-dd HH:mm:ss的形式
* @return
*/
public static String getCurDateTime()
{
return dateToDateString(new Date(), DATATIMEF_STR);
}
/**
* 获取当前日期时间yyyy年MM月dd日HH时mm分ss秒的形式
* @return
*/
public static String getCurZhCNDateTime()
{
return dateToDateString(new Date(), ZHCN_DATATIMEF_STR);
}
/**
* 获取日期d的days天后的一个Date
* @param d
* @param days
* @return
*/
public static Date getInternalDateByDay(Date d, int days)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
now.add(Calendar.DATE, days);
return now.getTime();
}
public static Date getInternalDateByMon(Date d, int months)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
now.add(Calendar.MONTH, months);
return now.getTime();
}
public static Date getInternalDateByYear(Date d, int years)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
now.add(Calendar.YEAR, years);
return now.getTime();
}
public static Date getInternalDateBySec(Date d, int sec)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
now.add(Calendar.SECOND, sec);
return now.getTime();
}
public static Date getInternalDateByMin(Date d, int min)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
now.add(Calendar.MINUTE, min);
return now.getTime();
}
public static Date getInternalDateByHour(Date d, int hours)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
now.add(Calendar.HOUR_OF_DAY, hours);
return now.getTime();
}
/**
* 根据一个日期字符串,返回日期格式,目前支持4种
* 如果都不是,则返回null
* @param DateString
* @return
*/
public static String getFormateStr(String DateString)
{
String patternStr1 = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}"; //"yyyy-MM-dd"
String patternStr2 = "[0-9]{4}-[0-9]{1,2}-[0-9]{1,2}\\s[0-9]{1,2}:[0-9]{1,2}:[0-9]{1,2}"; //"yyyy-MM-dd HH:mm:ss";
String patternStr3 = "[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日";//"yyyy年MM月dd日"
String patternStr4 = "[0-9]{4}年[0-9]{1,2}月[0-9]{1,2}日[0-9]{1,2}时[0-9]{1,2}分[0-9]{1,2}秒";//"yyyy年MM月dd日HH时mm分ss秒"
Pattern p = Pattern.compile(patternStr1);
Matcher m = p.matcher(DateString);
boolean b = m.matches();
if (b)
return DATAFORMAT_STR;
p = Pattern.compile(patternStr2);
m = p.matcher(DateString);
b = m.matches();
if (b)
return DATATIMEF_STR;
p = Pattern.compile(patternStr3);
m = p.matcher(DateString);
b = m.matches();
if (b)
return ZHCN_DATAFORMAT_STR;
p = Pattern.compile(patternStr4);
m = p.matcher(DateString);
b = m.matches();
if (b)
return ZHCN_DATATIMEF_STR;
return null;
}
/**
* 将一个"yyyy-MM-dd HH:mm:ss"字符串,转换成"yyyy年MM月dd日HH时mm分ss秒"的字符串
* @param dateStr
* @return
*/
public static String getZhCNDateTime(String dateStr)
{
Date d = getDate(dateStr);
return dateToDateString(d, ZHCN_DATATIMEF_STR);
}
/**
* 将一个"yyyy-MM-dd"字符串,转换成"yyyy年MM月dd日"的字符串
* @param dateStr
* @return
*/
public static String getZhCNDate(String dateStr)
{
Date d = getDate(dateStr, DATAFORMAT_STR);
return dateToDateString(d, ZHCN_DATAFORMAT_STR);
}
/**
* 将dateStr从fmtFrom转换到fmtTo的格式
* @param dateStr
* @param fmtFrom
* @param fmtTo
* @return
*/
public static String getDateStr(String dateStr, String fmtFrom, String fmtTo)
{
Date d = getDate(dateStr, fmtFrom);
return dateToDateString(d, fmtTo);
}
/**
* 比较两个"yyyy-MM-dd HH:mm:ss"格式的日期,之间相差多少毫秒,time2-time1
* @param time1
* @param time2
* @return
*/
public static long compareDateStr(String time1, String time2)
{
Date d1 = getDate(time1);
Date d2 = getDate(time2);
return d2.getTime() - d1.getTime();
}
/**
* 将小时数换算成返回以毫秒为单位的时间
* @param hours
* @return
*/
public static long getMicroSec(BigDecimal hours)
{
BigDecimal bd;
bd = hours.multiply(new BigDecimal(3600 * 1000));
return bd.longValue();
}
/**
* 获取Date中的分钟
* @param d
* @return
*/
public static int getMin(Date d)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
return now.get(Calendar.MINUTE);
}
/**
* 获取Date中的小时(24小时)
* @param d
* @return
*/
public static int getHour(Date d)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
return now.get(Calendar.HOUR_OF_DAY);
}
/**
* 获取Date中的秒
* @param d
* @return
*/
public static int getSecond(Date d)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
return now.get(Calendar.SECOND);
}
/**
* 获取xxxx-xx-xx的日
* @param d
* @return
*/
public static int getDay(Date d)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
return now.get(Calendar.DAY_OF_MONTH);
}
/**
* 获取月份,1-12月
* @param d
* @return
*/
public static int getMonth(Date d)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
return now.get(Calendar.MONTH) + 1;
}
/**
* 获取19xx,20xx形式的年
* @param d
* @return
*/
public static int getYear(Date d)
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
now.setTime(d);
return now.get(Calendar.YEAR);
}
/**
* 得到d的上个月的年份+月份,如200505
* @return
*/
public static String getYearMonthOfLastMon(Date d)
{
Date newdate = getInternalDateByMon(d, -1);
String year = String.valueOf(getYear(newdate));
String month = String.valueOf(getMonth(newdate));
return year + month;
}
/**
* 得到当前日期的年和月如200509
* @return String
*/
public static String getCurYearMonth()
{
Calendar now = Calendar.getInstance(TimeZone.getDefault());
String DATE_FORMAT = "yyyyMM";
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(DATE_FORMAT);
sdf.setTimeZone(TimeZone.getDefault());
return (sdf.format(now.getTime()));
}
public static Date getNextMonth(String year, String month)
{
String datestr = year + "-" + month + "-01";
Date date = getDate(datestr, DATAFORMAT_STR);
return getInternalDateByMon(date, 1);
}
public static Date getLastMonth(String year, String month)
{
String datestr = year + "-" + month + "-01";
Date date = getDate(datestr, DATAFORMAT_STR);
return getInternalDateByMon(date, -1);
}
/**
* 得到日期d,按照页面日期控件格式,如"2001-3-16"
* @param d
* @return
*/
public static String getSingleNumDate(Date d)
{
return dateToDateString(d, DATAFORMAT_STR);
}
/**
* 得到d半年前的日期,"yyyy-MM-dd"
* @param d
* @return
*/
public static String getHalfYearBeforeStr(Date d)
{
return dateToDateString(getInternalDateByMon(d, -6), DATAFORMAT_STR);
}
/**
* 得到当前日期D的月底的前/后若干天的时间,<0表示之前,>0表示之后
* @param d
* @param days
* @return
*/
public static String getInternalDateByLastDay(Date d, int days)
{
return dateToDateString(getInternalDateByDay(d, days), DATAFORMAT_STR);
}
/**
* 日期中的年月日相加
* @param field int 需要加的字段 年 月 日
* @param amount int 加多少
* @return String
*/
public static String addDate(int field, int amount)
{
int temp = 0;
if (field == 1)
{
temp = Calendar.YEAR;
}
if (field == 2)
{
temp = Calendar.MONTH;
}
if (field == 3)
{
temp = Calendar.DATE;
}
String Time = "";
try
{
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Calendar cal = Calendar.getInstance(TimeZone.getDefault());
cal.add(temp, amount);
Time = sdf.format(cal.getTime());
return Time;
}
catch (Exception e)
{
e.printStackTrace();
return null;
}
}
/**
* 获得系统当前月份的天数
* @return
*/
public static int getCurentMonthDay()
{
Date date = Calendar.getInstance().getTime();
return getMonthDay(date);
}
/**
* 获得指定日期月份的天数
* @return
*/
public static int getMonthDay(Date date)
{
Calendar c = Calendar.getInstance();
c.setTime(date);
return c.getActualMaximum(Calendar.DAY_OF_MONTH);
}
/**
* 获得指定日期月份的天数 yyyy-mm-dd
* @return
*/
public static int getMonthDay(String date)
{
Date strDate = getDate(date, DATAFORMAT_STR);
return getMonthDay(strDate);
}
public static String getStringDate(Calendar cal)
{
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
return format.format(cal.getTime());
}
/**
* @param args
*/
public static void main(String[] args)
{
// //System.out.print(DateUtil.getDate("04:04:04","HH:mm:ss"));
// System.out.print("\n"+DateUtil.getCurZhCNDateTime());
// System.out.print("\n"+getFormateStr(DateUtil.getCurDate()));
// System.out.print("\n"+compareDateStr("1900-1-1 1:1:2","1900-1-1 1:1:3"));
// System.out.print("\n"+getDay(new Date()));
// System.out.print("\n"+getMonth(new Date()));
// System.out.print("\n"+getYear(new Date()));
// System.out.print("\n"+getMin(new Date()));
System.out.print("\n"+new Date().getSeconds());
/*Date d1 = new Date(2007,11,30);
Date d2 = new Date(2007,12,1);
if(d2.compareTo(d1)>0){
System.out.println("d2大于d1");
}else{
System.out.println("d2小于d1");
}*/
System.out.println(addDate(1, 1));
System.out.println(addDate(2, 1));
System.out.println(addDate(3, 1));
System.out.println(getYYYYMMDDHHMMSSDate(new Date()));
System.out.println(getCurentMonthDay());
}
}