- 浏览: 145919 次
文章分类
最新评论
-
niwai:
你好我用httpclient4.2 登录亚马逊怎么提示没有激活 ...
用httpclient开发的在线自动抢订火车票系统(铁老大不给力,哥给力)
项目经验分享——Java常用工具类集合
写在前面
本文涉及的工具类部分是自己编写,另一部分是在项目里收集的。工具类涉及数据库连接、格式转换、文件操作、发送邮件等等。提高开发效率,欢迎收藏与转载。
数据库连接工具类
数据库连接工具类——仅仅获得连接对象 ConnDB.java
- packagecom.util;
- importjava.sql.Connection;
- importjava.sql.DriverManager;
- /**
- *数据库连接工具类——仅仅获得连接对象
- *
- */
- publicclassConnDB{
- privatestaticConnectionconn=null;
- privatestaticfinalStringDRIVER_NAME="com.mysql.jdbc.Driver";
- privatestaticfinalStringURL="jdbc:mysql://localhost:3306/axt?useUnicode=true&characterEncoding=UTF-8";
- privatestaticfinalStringUSER_NAME="root";
- privatestaticfinalStringPASSWORD="root";
- publicstaticConnectiongetConn(){
- try{
- Class.forName(DRIVER_NAME);
- conn=DriverManager.getConnection(URL,USER_NAME,PASSWORD);
- }catch(Exceptione){
- e.printStackTrace();
- }
- returnconn;
- }
- }
数据库连接工具类——包含取得连接和关闭资源 ConnUtil.java
- packagecom.util;
- importjava.sql.Connection;
- importjava.sql.DriverManager;
- importjava.sql.PreparedStatement;
- importjava.sql.ResultSet;
- importjava.sql.SQLException;
- /**
- *@className:ConnUtil.java
- *@classDescription:数据库连接工具类——包含取得连接和关闭资源
- *@function:
- *@author:Wentasy
- *@createTime:2012-9-24上午11:51:15
- *@modifyTime:
- *@modifyReason:
- *@since:JDK1.6
- */
- publicclassConnUtil{
- publicstaticfinalStringurl="jdbc:mysql://XXX.XXX.XXX.XXX:3306/dbadapter";
- publicstaticfinalStringuser="root";
- publicstaticfinalStringpassword="XXXXXX";
- /**
- *得到连接
- *@return
- *@throwsSQLException
- *@throwsClassNotFoundException
- */
- publicstaticConnectionestablishConn()throwsSQLException,ClassNotFoundException{
- Class.forName("com.mysql.jdbc.Driver");
- returnDriverManager.getConnection(url,user,password);
- }
- /**
- *关闭连接
- *@paramconn
- *@throwsSQLException
- */
- publicstaticvoidclose(Connectionconn)throwsSQLException{
- if(conn!=null){
- conn.close();
- conn=null;
- }
- }
- /**
- *关闭PreparedStatement
- *@parampstmt
- *@throwsSQLException
- */
- publicstaticvoidclose(PreparedStatementpstmt)throwsSQLException{
- if(pstmt!=null){
- pstmt.close();
- pstmt=null;
- }
- }
- /**
- *关闭结果集
- *@paramrs
- *@throwsSQLException
- */
- publicstaticvoidclose(ResultSetrs)throwsSQLException{
- if(rs!=null){
- rs.close();
- rs=null;
- }
- }
- }
格式转换工具类
日期转换工具类 CommUtil.java
- packagecom.util;
- importjava.text.ParseException;
- importjava.text.SimpleDateFormat;
- importjava.util.Date;
- /**
- *日期转换工具类
- */
- publicclassCommUtil{
- /**
- *将日期格式转换成yyyy-MM-dd的字符串格式
- *返回值如:2010-10-06
- *@paramtime要转换的日期
- *@return
- */
- publicstaticStringdateToString(Datetime){
- SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd");//定义将日期格式要换成的格式
- StringstringTime=formatter.format(time);
- returnstringTime;
- }
- /**
- *将日期格式转换成yyyyMMdd的字符串格式
- *返回值如:2010-10-06
- *@paramtime要转换的日期
- *@return
- */
- publicstaticStringdateTimeToString(Datetime){
- SimpleDateFormatformatter=newSimpleDateFormat("yyyyMMdd");//定义将日期格式要换成的格式
- StringstringTime=formatter.format(time);
- returnstringTime;
- }
- /**
- *将日期格式转换成yyyy-MM-dd的字符串格式
- *返回值如:2010-10-06
- *@paramtime要转换的日期
- *@return
- */
- publicstaticDatedateToDate(Datetime){
- SimpleDateFormatformatter=newSimpleDateFormat("yyyy-MM-dd");//定义将日期格式要换成的格式
- StringstringTime=formatter.format(time);
- Datedate=null;
- try{
- date=formatter.parse(stringTime);
- }catch(ParseExceptione){
- e.printStackTrace();
- }
- returndate;
- }
- /**
- *得到当前时间,以字符串表示
- *@return
- */
- publicstaticStringgetDate(){
- Datedate=newDate();
- returnCommUtil.dateToString(date);
- }
- }
日期转换类 DateConverter.java
- packagecom.util;
- importjava.text.DateFormat;
- importjava.text.SimpleDateFormat;
- importjava.util.Date;
- importjava.util.Map;
- importcom.opensymphony.xwork2.conversion.impl.DefaultTypeConverter;
- /**
- *日期转换类
- *
- */
- publicclassDateConverterextendsDefaultTypeConverter{
- privatestaticfinalDateFormat[]ACCEPT_DATE_FORMATS={
- newSimpleDateFormat("dd/MM/yyyy"),
- newSimpleDateFormat("yyyy-MM-dd"),
- newSimpleDateFormat("yyyy/MM/dd")};//支持转换的日期格式
- @Override
- publicObjectconvertValue(Mapcontext,Objectvalue,ClasstoType){
- if(toType==Date.class){//浏览器向服务器提交时,进行StringtoDate的转换
- Datedate=null;
- StringdateString=null;
- String[]params=(String[])value;
- dateString=params[0];//获取日期的字符串
- for(DateFormatformat:ACCEPT_DATE_FORMATS){
- try{
- returnformat.parse(dateString);//遍历日期支持格式,进行转换
- }catch(Exceptione){
- continue;
- }
- }
- returnnull;
- }
- elseif(toType==String.class){//服务器向浏览器输出时,进行DatetoString的类型转换
- Datedate=(Date)value;
- returnnewSimpleDateFormat("yyyy-MM-dd").format(date);//输出的格式是yyyy-MM-dd
- }
- returnnull;
- }
- }
功能更强大的格式化工具类 FormatUtils.java
- packagecom.util;
- importjava.text.DecimalFormat;
- importjava.text.ParseException;
- importjava.text.SimpleDateFormat;
- importjava.util.Date;
- /**
- *功能更强大的格式化工具类
- */
- publicclassFormatUtils{
- privatestaticSimpleDateFormatsecond=newSimpleDateFormat(
- "yy-MM-ddhh:mm:ss");
- privatestaticSimpleDateFormatday=newSimpleDateFormat("yyyy-MM-dd");
- privatestaticSimpleDateFormatdetailDay=newSimpleDateFormat("yyyy年MM月dd日");
- privatestaticSimpleDateFormatfileName=newSimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
- privatestaticSimpleDateFormattempTime=newSimpleDateFormat("yyyy-MM-ddHH:mm:ss");
- privatestaticSimpleDateFormatexcelDate=newSimpleDateFormat("yyyy/MM/dd");
- /**
- *格式化excel中的时间
- *@paramdate
- *@return
- */
- publicstaticStringformatDateForExcelDate(Datedate){
- returnexcelDate.format(date);
- }
- /**
- *将日期格式化作为文件名
- *@paramdate
- *@return
- */
- publicstaticStringformatDateForFileName(Datedate){
- returnfileName.format(date);
- }
- /**
- *格式化日期(精确到秒)
- *
- *@paramdate
- *@return
- */
- publicstaticStringformatDateSecond(Datedate){
- returnsecond.format(date);
- }
- /**
- *格式化日期(精确到秒)
- *
- *@paramdate
- *@return
- */
- publicstaticStringtempDateSecond(Datedate){
- returntempTime.format(date);
- }
- publicstaticDatetempDateSecond(Stringstr){
- try{
- returntempTime.parse(str);
- }catch(ParseExceptione){
- e.printStackTrace();
- }
- returnnewDate();
- }
- /**
- *格式化日期(精确到天)
- *
- *@paramdate
- *@return
- */
- publicstaticStringformatDateDay(Datedate){
- returnday.format(date);
- }
- /**
- *格式化日期(精确到天)
- *
- *@paramdate
- *@return
- */
- publicstaticStringformatDateDetailDay(Datedate){
- returndetailDay.format(date);
- }
- /**
- *将double类型的数字保留两位小数(四舍五入)
- *
- *@paramnumber
- *@return
- */
- publicstaticStringformatNumber(doublenumber){
- DecimalFormatdf=newDecimalFormat();
- df.applyPattern("#0.00");
- returndf.format(number);
- }
- /**
- *将字符串转换成日期
- *
- *@paramdate
- *@return
- *@throwsException
- */
- publicstaticDateformateDate(Stringdate)throwsException{
- returnday.parse(date);
- }
- /**
- *将字符日期转换成Date
- *@paramdate
- *@return
- *@throwsException
- */
- publicstaticDateparseStringToDate(Stringdate)throwsException{
- returnday.parse(date);
- }
- publicstaticStringformatDoubleNumber(doublenumber){
- DecimalFormatdf=newDecimalFormat("#");
- returndf.format(number);
- }
- }
文件操作工具类
目录操作工具类 CopyDir.java
- packagecom.util;
- importjava.io.*;
- /**
- *1,建立目的目录。2,遍历源目录。3,遍历过程中,创建文件或者文件夹。原理:其实就是改变了源文件或者目录的目录头。
- *@datetimeDsc24
- */
- publicclassCopyDir{
- privateFilesDir,dDir,newDir;
- publicCopyDir(Strings,Stringd){
- this(newFile(s),newFile(d));
- }
- CopyDir(FilesDir,FiledDir)//c:\\Testd:\\abc
- {
- this.sDir=sDir;
- this.dDir=dDir;
- }
- publicvoidcopyDir()throwsIOException{
- //是创建目的目录。也就是创建要拷贝的源文件夹。Test
- //获取源文件夹名称。
- Stringname=sDir.getName();
- //通过该名称在目的目录创建该文件夹,为了存放源文件夹中的文件或者文件夹。
- //将目的目录和源文件夹名称,封装成File对象。
- newDir=dDir;
- //newFile(dDir,name);
- //调用该对象的mkdir方法。在目的目录创建该文件夹。d:\\abc\\Test
- newDir.mkdir();//
- //遍历源文件夹。
- listAll(sDir);
- }
- /*
- *将遍历目录封装成方法。在遍历过程中,遇到文件创建文件。遇到目录创建目录。
- */
- privatevoidlistAll(Filedir)throwsIOException{
- File[]files=dir.listFiles();
- for(intx=0;x<files.length;x++){
- if(files[x].isDirectory()){
- createDir(files[x]);//调用创建目录的方法。
- listAll(files[x]);//在继续进行递归。进入子级目录。
- }else{
- createFile(files[x]);//调用创建文件的方法。
- }
- }
- }
- /*
- *copy目录。通过源目录在目的目录创建新目录。
- */
- privatevoidcreateDir(Filedir){
- Filed=replaceFile(dir);
- d.mkdir();
- }
- /*
- *copy文件。
- */
- privatevoidcreateFile(Filefile)throwsIOException{
- FilenewFile=replaceFile(file);
- //copy文件是一个数据数据传输的过程。需要通过流来完成。
- FileInputStreamfis=newFileInputStream(file);
- FileOutputStreamfos=newFileOutputStream(newFile);
- byte[]buf=newbyte[1024*2];
- intnum=0;
- while((num=fis.read(buf))!=-1){
- fos.write(buf,0,num);
- }
- fos.close();
- fis.close();
- }
- /*
- *替换路径。
- */
- privateFilereplaceFile(Filef){
- //原理是:将源目录的父目录(C:\\Tset),替换成目的父目录。(d:\\abc\\Test)
- Stringpath=f.getAbsolutePath();//获取源文件或者文件夹的决定路径。
- //将源文件或者文件夹的绝对路径替换成目的路径。
- StringnewPath=path.replace(sDir.getAbsolutePath(),newDir
- .getAbsolutePath());
- //将新的目的路径封装成File对象
- FilenewFile=newFile(newPath);
- returnnewFile;
- }
- }
文件/目录部分处理工具类 DealDir.java
- packagecom.util;
- importjava.io.File;
- importjava.util.StringTokenizer;
- /**
- *文件/目录部分处理
- *@createTimeDec25,20107:06:58AM
- *@version1.0
- */
- publicclassDealDir{
- /**
- *获取文件的后缀名并转化成大写
- *
- *@paramfileName
- *文件名
- *@return
- */
- publicStringgetFileSuffix(StringfileName)throwsException{
- returnfileName.substring(fileName.lastIndexOf(".")+1,
- fileName.length()).toUpperCase();
- }
- /**
- *创建多级目录
- *
- *@parampath
- *目录的绝对路径
- */
- publicvoidcreateMultilevelDir(Stringpath){
- try{
- StringTokenizerst=newStringTokenizer(path,"/");
- Stringpath1=st.nextToken()+"/";
- Stringpath2=path1;
- while(st.hasMoreTokens()){
- path1=st.nextToken()+"/";
- path2+=path1;
- Fileinbox=newFile(path2);
- if(!inbox.exists())
- inbox.mkdir();
- }
- }catch(Exceptione){
- System.out.println("目录创建失败"+e);
- e.printStackTrace();
- }
- }
- /**
- *删除文件/目录(递归删除文件/目录)
- *
- *@parampath
- *文件或文件夹的绝对路径
- */
- publicvoiddeleteAll(Stringdirpath){
- if(dirpath==null){
- System.out.println("目录为空");
- }else{
- Filepath=newFile(dirpath);
- try{
- if(!path.exists())
- return;//目录不存在退出
- if(path.isFile())//如果是文件删除
- {
- path.delete();
- return;
- }
- File[]files=path.listFiles();//如果目录中有文件递归删除文件
- for(inti=0;i<files.length;i++){
- deleteAll(files[i].getAbsolutePath());
- }
- path.delete();
- }catch(Exceptione){
- System.out.println("文件/目录删除失败"+e);
- e.printStackTrace();
- }
- }
- }
- /**
- *文件/目录重命名
- *
- *@paramoldPath
- *原有路径(绝对路径)
- *@paramnewPath
- *更新路径
- *@authorlyf注:不能修改上层次的目录
- */
- publicvoidrenameDir(StringoldPath,StringnewPath){
- FileoldFile=newFile(oldPath);//文件或目录
- FilenewFile=newFile(newPath);//文件或目录
- try{
- booleansuccess=oldFile.renameTo(newFile);//重命名
- if(!success){
- System.out.println("重命名失败");
- }else{
- System.out.println("重命名成功");
- }
- }catch(RuntimeExceptione){
- e.printStackTrace();
- }
- }
- }
目录处理工具类 DealWithDir.java
- packagecom.util;
- importjava.io.File;
- /**
- *目录处理工具类
- *
- */
- publicclassDealWithDir{
- /**
- *新建目录
- */
- publicstaticbooleannewDir(Stringpath)throwsException{
- Filefile=newFile(path);
- returnfile.mkdirs();//创建目录
- }
- /**
- *删除目录
- */
- publicstaticbooleandeleteDir(Stringpath)throwsException{
- Filefile=newFile(path);
- if(!file.exists())
- returnfalse;//目录不存在退出
- if(file.isFile())//如果是文件删除
- {
- file.delete();
- returnfalse;
- }
- File[]files=file.listFiles();//如果目录中有文件递归删除文件
- for(inti=0;i<files.length;i++){
- deleteDir(files[i].getAbsolutePath());
- }
- file.delete();
- returnfile.delete();//删除目录
- }
- /**
- *更新目录
- */
- publicstaticbooleanupdateDir(Stringpath,StringnewPath)throwsException{
- Filefile=newFile(path);
- FilenewFile=newFile(newPath);
- returnfile.renameTo(newFile);
- }
- publicstaticvoidmain(Stringd[])throwsException{
- //deleteDir("d:/ff/dddf");
- updateDir("D:\\TOOLS\\Tomcat6.0\\webapps\\BCCCSM\\nationalExperiment/22222","D:\\TOOLS\\Tomcat6.0\\webapps\\BCCCSM\\nationalExperiment/224222");
- }
- }
删除文件夹工具类 DeleteFolder.java
- packagecom.util;
- importjava.io.File;
- /**
- *删除文件夹
- *@createTimeDSC20,201015:38
- *@version2.0
- */
- publicclassDeleteFolder{
- //删除文件夹
- //paramfolderPath文件夹完整绝对路径
- publicstaticvoiddelFolder(StringfolderPath){
- try{
- delAllFile(folderPath);//删除完里面所有内容
- StringfilePath=folderPath;
- filePath=filePath.toString();
- java.io.FilemyFilePath=newjava.io.File(filePath);
- myFilePath.delete();//删除空文件夹
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- //删除指定文件夹下所有文件
- //parampath文件夹完整绝对路径
- publicstaticbooleandelAllFile(Stringpath){
- booleanflag=false;
- Filefile=newFile(path);
- if(!file.exists()){
- returnflag;
- }
- if(!file.isDirectory()){
- returnflag;
- }
- String[]tempList=file.list();
- Filetemp=null;
- for(inti=0;i<tempList.length;i++){
- if(path.endsWith(File.separator)){
- temp=newFile(path+tempList[i]);
- }else{
- temp=newFile(path+File.separator+tempList[i]);
- }
- if(temp.isFile()){
- temp.delete();
- }
- if(temp.isDirectory()){
- delAllFile(path+"/"+tempList[i]);//先删除文件夹里面的文件
- delFolder(path+"/"+tempList[i]);//再删除空文件夹
- flag=true;
- }
- }
- returnflag;
- }
- }
文件上传工具类 UploadUtil.java
- packagecom.util;
- importjava.io.BufferedInputStream;
- importjava.io.BufferedOutputStream;
- importjava.io.File;
- importjava.io.FileInputStream;
- importjava.io.FileOutputStream;
- importjava.io.InputStream;
- importjava.io.OutputStream;
- importjava.util.Calendar;
- /**
- *文件上传工具类
- *
- */
- publicclassUploadUtil{
- privatestaticfinalintBUFFER_SIZE=16*1024;
- //保存图片
- publicstaticsynchronizedvoidcopy(Filesrc,FilenewFile){
- try{
- InputStreamis=null;
- OutputStreamos=null;
- try{
- is=newBufferedInputStream(newFileInputStream(src),
- BUFFER_SIZE);
- os=newBufferedOutputStream(newFileOutputStream(newFile),
- BUFFER_SIZE);
- byte[]buffer=newbyte[BUFFER_SIZE];
- while(is.read(buffer)>0){
- os.write(buffer);
- }
- }finally{
- if(null!=is){
- is.close();
- }
- if(null!=os){
- os.close();
- }
- }
- }catch(Exceptione){
- e.printStackTrace();
- }
- }
- /**
- *返回年号+月号+天+时+分+秒+随机码
- *@return
- */
- @SuppressWarnings("static-access")
- publicstaticsynchronizedStringgetTime(){
- Calendarcalendar=Calendar.getInstance();
- Stringyear=calendar.get(calendar.YEAR)+"";
- Stringmonth=(calendar.get(calendar.MONTH)+1)+"";
- Stringday=calendar.get(calendar.DAY_OF_MONTH)+"";
- Stringhour=calendar.get(calendar.HOUR_OF_DAY)+"";
- Stringminute=calendar.get(calendar.MINUTE)+"";
- Stringsecond=calendar.get(calendar.SECOND)+"";
- StringmilliSecond=calendar.get(calendar.MILLISECOND)+"";
- intr=(int)(Math.random()*100000);
- Stringrandom=String.valueOf(r);
- returnyear+month+day+hour+minute+second+milliSecond+random+"a";
- }
- }
其他工具类
MD5编码工具类 MD5Code.java
- packagecom.util;
- /**
- *MD5编码工具类
- *
- */
- publicclassMD5Code{
- staticfinalintS11=7;
- staticfinalintS12=12;
- staticfinalintS13=17;
- staticfinalintS14=22;
- staticfinalintS21=5;
- staticfinalintS22=9;
- staticfinalintS23=14;
- staticfinalintS24=20;
- staticfinalintS31=4;
- staticfinalintS32=11;
- staticfinalintS33=16;
- staticfinalintS34=23;
- staticfinalintS41=6;
- staticfinalintS42=10;
- staticfinalintS43=15;
- staticfinalintS44=21;
- staticfinalbyte[]PADDING={-128,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,
- 0,0,0,0,0,0,0};
- privatelong[]state=newlong[4];//state(ABCD)
- privatelong[]count=newlong[2];//numberofbits,modulo2^64(lsb
- //first)
- privatebyte[]buffer=newbyte[64];//inputbuffer
- publicStringdigestHexStr;
- privatebyte[]digest=newbyte[16];
- publicStringgetMD5ofStr(Stringinbuf){
- md5Init();
- md5Update(inbuf.getBytes(),inbuf.length());
- md5Final();
- digestHexStr="";
- for(inti=0;i<16;i++){
- digestHexStr+=byteHEX(digest[i]);
- }
- returndigestHexStr;
- }
- publicMD5Code(){
- md5Init();
- return;
- }
- privatevoidmd5Init(){
- count[0]=0L;
- count[1]=0L;
- ///*Loadmagicinitializationconstants.
- state[0]=0x67452301L;
- state[1]=0xefcdab89L;
- state[2]=0x98badcfeL;
- state[3]=0x10325476L;
- return;
- }
- privatelongF(longx,longy,longz){
- return(x&y)|((~x)&z);
- }
- privatelongG(longx,longy,longz){
- return(x&z)|(y&(~z));
- }
- privatelongH(longx,longy,longz){
- returnx^y^z;
- }
- privatelongI(longx,longy,longz){
- returny^(x|(~z));
- }
- privatelongFF(longa,longb,longc,longd,longx,longs,longac){
- a+=F(b,c,d)+x+ac;
- a=((int)a<<s)|((int)a>>>(32-s));
- a+=b;
- returna;
- }
- privatelongGG(longa,longb,longc,longd,longx,longs,longac){
- a+=G(b,c,d)+x+ac;
- a=((int)a<<s)|((int)a>>>(32-s));
- a+=b;
- returna;
- }
- privatelongHH(longa,longb,longc,longd,longx,longs,longac){
- a+=H(b,c,d)+x+ac;
- a=((int)a<<s)|((int)a>>>(32-s));
- a+=b;
- returna;
- }
- privatelongII(longa,longb,longc,longd,longx,longs,longac){
- a+=I(b,c,d)+x+ac;
- a=((int)a<<s)|((int)a>>>(32-s));
- a+=b;
- returna;
- }
- privatevoidmd5Update(byte[]inbuf,intinputLen){
- inti,index,partLen;
- byte[]block=newbyte[64];
- index=(int)(count[0]>>>3)&0x3F;
- ///*Updatenumberofbits*/
- if((count[0]+=(inputLen<<3))<(inputLen<<3))
- count[1]++;
- count[1]+=(inputLen>>>29);
- partLen=64-index;
- //Transformasmanytimesaspossible.
- if(inputLen>=partLen){
- md5Memcpy(buffer,inbuf,index,0,partLen);
- md5Transform(buffer);
- for(i=partLen;i+63<inputLen;i+=64){
- md5Memcpy(block,inbuf,0,i,64);
- md5Transform(block);
- }
- index=0;
- }else
- i=0;
- ///*Bufferremaininginput*/
- md5Memcpy(buffer,inbuf,index,i,inputLen-i);
- }
- privatevoidmd5Final(){
- byte[]bits=newbyte[8];
- intindex,padLen;
- ///*Savenumberofbits*/
- Encode(bits,count,8);
- ///*Padoutto56mod64.
- index=(int)(count[0]>>>3)&0x3f;
- padLen=(index<56)?(56-index):(120-index);
- md5Update(PADDING,padLen);
- ///*Appendlength(beforepadding)*/
- md5Update(bits,8);
- ///*Storestateindigest*/
- Encode(digest,state,16);
- }
- privatevoidmd5Memcpy(byte[]output,byte[]input,intoutpos,intinpos,
- intlen){
- inti;
- for(i=0;i<len;i++)
- output[outpos+i]=input[inpos+i];
- }
- privatevoidmd5Transform(byteblock[]){
- longa=state[0],b=state[1],c=state[2],d=state[3];
- long[]x=newlong[16];
- Decode(x,block,64);
- /*Round1*/
- a=FF(a,b,c,d,x[0],S11,0xd76aa478L);/*1*/
- d=FF(d,a,b,c,x[1],S12,0xe8c7b756L);/*2*/
- c=FF(c,d,a,b,x[2],S13,0x242070dbL);/*3*/
- b=FF(b,c,d,a,x[3],S14,0xc1bdceeeL);/*4*/
- a=FF(a,b,c,d,x[4],S11,0xf57c0fafL);/*5*/
- d=FF(d,a,b,c,x[5],S12,0x4787c62aL);/*6*/
- c=FF(c,d,a,b,x[6],S13,0xa8304613L);/*7*/
- b=FF(b,c,d,a,x[7],S14,0xfd469501L);/*8*/
- a=FF(a,b,c,d,x[8],S11,0x698098d8L);/*9*/
- d=FF(d,a,b,c,x[9],S12,0x8b44f7afL);/*10*/
- c=FF(c,d,a,b,x[10],S13,0xffff5bb1L);/*11*/
- b=FF(b,c,d,a,x[11],S14,0x895cd7beL);/*12*/
- a=FF(a,b,c,d,x[12],S11,0x6b901122L);/*13*/
- d=FF(d,a,b,c,x[13],S12,0xfd987193L);/*14*/
- c=FF(c,d,a,b,x[14],S13,0xa679438eL);/*15*/
- b=FF(b,c,d,a,x[15],S14,0x49b40821L);/*16*/
- /*Round2*/
- a=GG(a,b,c,d,x[1],S21,0xf61e2562L);/*17*/
- d=GG(d,a,b,c,x[6],S22,0xc040b340L);/*18*/
- c=GG(c,d,a,b,x[11],S23,0x265e5a51L);/*19*/
- b=GG(b,c,d,a,x[0],S24,0xe9b6c7aaL);/*20*/
- a=GG(a,b,c,d,x[5],S21,0xd62f105dL);/*21*/
- d=GG(d,a,b,c,x[10],S22,0x2441453L);/*22*/
- c=GG(c,d,a,b,x[15],S23,0xd8a1e681L);/*23*/
- b=GG(b,c,d,a,x[4],S24,0xe7d3fbc8L);/*24*/
- a=GG(a,b,c,d,x[9],S21,0x21e1cde6L);/*25*/
- d=GG(d,a,b,c,x[14],S22,0xc33707d6L);/*26*/
- c=GG(c,d,a,b,x[3],S23,0xf4d50d87L);/*27*/
- b=GG(b,c,d,a,x[8],S24,0x455a14edL);/*28*/
- a=GG(a,b,c,d,x[13],S21,0xa9e3e905L);/*29*/
- d=GG(d,a,b,c,x[2],S22,0xfcefa3f8L);/*30*/
- c=GG(c,d,a,b,x[7],S23,0x676f02d9L);/*31*/
- b=GG(b,c,d,a,x[12],S24,0x8d2a4c8aL);/*32*/
- /*Round3*/
- a=HH(a,b,c,d,x[5],S31,0xfffa3942L);/*33*/
- d=HH(d,a,b,c,x[8],S32,0x8771f681L);/*34*/
- c=HH(c,d,a,b,x[11],S33,0x6d9d6122L);/*35*/
- b=HH(b,c,d,a,x[14],S34,0xfde5380cL);/*36*/
- a=HH(a,b,c,d,x[1],S31,0xa4beea44L);/*37*/
- d=HH(d,a,b,c,x[4],S32,0x4bdecfa9L);/*38*/
- c=HH(c,d,a,b,x[7],S33,0xf6bb4b60L);/*39*/
- b=HH(b,c,d,a,x[10],S34,0xbebfbc70L);/*40*/
- a=HH(a,b,c,d,x[13],S31,0x289b7ec6L);/*41*/
- d=HH(d,a,b,c,x[0],S32,0xeaa127faL);/*42*/
- c=HH(c,d,a,b,x[3],S33,0xd4ef3085L);/*43*/
- b=HH(b,c,d,a,x[6],S34,0x4881d05L);/*44*/
- a=HH(a,b,c,d,x[9],S31,0xd9d4d039L);/*45*/
- d=HH(d,a,b,c,x[12],S32,0xe6db99e5L);/*46*/
- c=HH(c,d,a,b,x[15],S33,0x1fa27cf8L);/*47*/
- b=HH(b,c,d,a,x[2],S34,0xc4ac5665L);/*48*/
- /*Round4*/
- a=II(a,b,c,d,x[0],S41,0xf4292244L);/*49*/
- d=II(d,a,b,c,x[7],S42,0x432aff97L);/*50*/
- c=II(c,d,a,b,x[14],S43,0xab9423a7L);/*51*/
- b=II(b,c,d,a,x[5],S44,0xfc93a039L);/*52*/
- a=II(a,b,c,d,x[12],S41,0x655b59c3L);/*53*/
- d=II(d,a,b,c,x[3],S42,0x8f0ccc92L);/*54*/
- c=II(c,d,a,b,x[10],S43,0xffeff47dL);/*55*/
- b=II(b,c,d,a,x[1],S44,0x85845dd1L);/*56*/
- a=II(a,b,c,d,x[8],S41,0x6fa87e4fL);/*57*/
- d=II(d,a,b,c,x[15],S42,0xfe2ce6e0L);/*58*/
- c=II(c,d,a,b,x[6],S43,0xa3014314L);/*59*/
- b=II(b,c,d,a,x[13],S44,0x4e0811a1L);/*60*/
- a=II(a,b,c,d,x[4],S41,0xf7537e82L);/*61*/
- d=II(d,a,b,c,x[11],S42,0xbd3af235L);/*62*/
- c=II(c,d,a,b,x[2],S43,0x2ad7d2bbL);/*63*/
- b=II(b,c,d,a,x[9],S44,0xeb86d391L);/*64*/
- state[0]+=a;
- state[1]+=b;
- state[2]+=c;
- state[3]+=d;
- }
- privatevoidEncode(byte[]output,long[]input,intlen){
- inti,j;
- for(i=0,j=0;j<len;i++,j+=4){
- output[j]=(byte)(input[i]&0xffL);
- output[j+1]=(byte)((input[i]>>>8)&0xffL);
- output[j+2]=(byte)((input[i]>>>16)&0xffL);
- output[j+3]=(byte)((input[i]>>>24)&0xffL);
- }
- }
- privatevoidDecode(long[]output,byte[]input,intlen){
- inti,j;
- for(i=0,j=0;j<len;i++,j+=4)
- output[i]=b2iu(input[j])|(b2iu(input[j+1])<<8)
- |(b2iu(input[j+2])<<16)|(b2iu(input[j+3])<<24);
- return;
- }
- publicstaticlongb2iu(byteb){
- returnb<0?b&0x7F+128:b;
- }
- publicstaticStringbyteHEX(byteib){
- char[]Digit={'0','1','2','3','4','5','6','7','8','9','A',
- 'B','C','D','E','F'};
- char[]ob=newchar[2];
- ob[0]=Digit[(ib>>>4)&0X0F];
- ob[1]=Digit[ib&0X0F];
- Strings=newString(ob);
- returns;
- }
- }
读取Config文件工具类 PropertiesConfig.java
- packagecom.util;
- importjava.io.BufferedInputStream;
- importjava.io.FileInputStream;
- importjava.io.InputStream;
- importjava.util.Properties;
- /**
- *读取Config文件工具类
- *@version1.0
- *@sinceJDK1.6
- */
- publicclassPropertiesConfig{
- /**
- *获取整个配置文件中的属性
- *@paramfilePath文件路径,即文件所在包的路径,例如:java/util/config.properties
- */
- publicstaticPropertiesreadData(StringfilePath){
- filePath=getRealPath(filePath);
- Propertiesprops=newProperties();
- try{
- InputStreamin=newBufferedInputStream(newFileInputStream(filePath));
- props.load(in);
- in.close();
- returnprops;
- }catch(Exceptione){
- e.printStackTrace();
- returnnull;
- }
- }
- privatestaticStringgetRealPath(StringfilePath){
- //获取绝对路径并截掉路径的”file:/“前缀
- returnPropertiesConfig.class.getResource("/"+filePath).toString().substring(6);
- }
- }
自动扫描FTP文件工具类 ScanFtp.java
- packagecom.util;
- importjava.io.BufferedInputStream;
- importjava.io.BufferedOutputStream;
- importjava.io.File;
- importjava.io.FileInputStream;
- importjava.io.FileOutputStream;
- importjava.io.IOException;
- /**
- *自动扫描FTP文件工具类
- *需要定时执行
- */
- publicclassScanFtp{
- //服务器图片路径文件夹
- privateStringserverLocal="D:/TOOLS/Tomcat6.0/webapps/BCCCSM/modelforcast/";
- //图片上传文件夹存放路径,文件夹内应包含AGCMCSMZS3个子文件夹分别存放需要扫描到tomcat中的图片
- privateStringsaveLocal="D:/modelForcast/";
- /**
- *获得远程权限
- *@return
- */
- privatevoidgetFTPAdress(){
- //登陆成功
- }
- /**
- *开始扫描
- *@throwsIOException
- */
- privatevoidscan()throwsIOException{
- this.getFTPAdress();
- Filefile=newFile(saveLocal+"AGCM");//打开AGCM
- File[]array=file.listFiles();
- StringfileName;
- FilefileTemp;
- for(inti=0;i<array.length;i++){
- if(array[i].isFile()){
- fileTemp=array[i];
- fileName=fileTemp.getName();//取出文件名
- if(!fileName.equals("humbs.db")){
- this.saveFile(fileTemp,1);//分析每一个文件名字并存储
- System.out.println(fileName+"saved");
- }
- }
- }
- file=newFile(saveLocal+"CSM");//打开CSM
- array=file.listFiles();
- for(inti=0;i<array.length;i++){
- if(array[i].isFile()){
- fileTemp=array[i];
- fileName=fileTemp.getName();//取出文件名
- if(!fileName.equals("humbs.db")){
- this.saveFile(fileTemp,2);//分析每一个文件名字并存储
- System.out.println(fileName+"saved");
- }
- }
- }
- file=newFile(saveLocal+"ZS");//打开ZS
- array=file.listFiles();
- for(inti=0;i<array.length;i++){
- if(array[i].isFile()){
- fileTemp=array[i];
- fileName=fileTemp.getName();//取出文件名
- if(!fileName.equals("humbs.db")){
- this.saveFile(fileTemp,3);//分析每一个文件名字并存储
- System.out.println(fileName+"saved");
- }
- }
- }
- }
- /**
- *开始执行
- *@throwsIOException
- */
- publicvoidexecute()throwsIOException{
- scan();//开始扫描
- }
- /**
- *按类型存储
- *@paramfile
- *@paramtype
- *@throwsIOException
- */
- privatevoidsaveFile(Filefile,inttype)throwsIOException{
- StringfileName=file.getName();
- //类型AC和指数3种
- Stringyear=fileName.substring(1,5);//获得发布年份
- Stringdate=fileName.substring(5,9);//获得发布日期包含月日
- Stringvar=null;//获得变量名字
- Stringdir=serverLocal;//存储目录名字
- if(type==1){
- var=fileName.substring(11,15);
- dir=dir+"AGCM/"+var+"/"+year+"/"+date;
- }elseif(type==2){
- var=fileName.substring(11,15);
- dir=dir+"CSM/"+var+"/"+year+"/"+date;
- }else{
- var=fileName.substring(11,15);//指数的暂时没处理
- dir=dir+"ZS/"+var+"/"+year+"/"+date;
- }
- //判断是否存在这样的目录没有就自动创建
- FilesavePath=newFile(dir);
- if(!savePath.exists()){
- savePath.mkdirs();
- }
- FilesaveFile=newFile(dir+"/"+fileName);
- if(!saveFile.exists()){//如果不存在,就存文件
- FileInputStreamfis=null;//这里用本地复制暂时代替FTP
- FileOutputStreamfos=null;
- BufferedInputStreambis=null;
- BufferedOutputStreambos=null;
- intc;
- fis=newFileInputStream(file);
- bis=newBufferedInputStream(fis);
- fos=newFileOutputStream(dir+"/"+fileName);
- bos=newBufferedOutputStream(fos);
- while((c=bis.read())!=-1)
- bos.write(c);
- bos.flush();
- if(bos!=null)bos.close();
- if(bis!=null)bis.close();
- if(fos!=null)fos.close();
- if(fis!=null)fos.close();
- }else{
- System.out.println("文件已经存在,不进行存储,可清理当前文件.");
- }
- }
- /**
- *测试方法
- *@paramargv
- *@throwsIOException
- */
- publicstaticvoidmain(Stringargv[]){
- ScanFtps=newScanFtp();
- try{
- s.scan();
- }catch(IOExceptione){
- //TODOAuto-generatedcatchblock
- e.printStackTrace();
- }
- }
- }
邮件发送工具类 SendMail.java
- packagecom.util;
- importorg.apache.commons.mail.EmailException;
- importorg.apache.commons.mail.SimpleEmail;
- /**
- *邮件发送工具类
- */
- publicclassSendMail{
- privateStringhostName;//设置smtp服务器
- privateStringsendMailAddress;//设置发送地址
- privateStringmailPassword;//设置密码
- privatebooleanTLS=false;//设置是否需要TLS登录
- privateString[]getMailAddress;//设置接收地址s
- privateStringmailTitle;//设置标题
- privateStringmailContent;//设置邮件内容
- publicvoidsend(){
- SimpleEmailemail=newSimpleEmail();
- email.setTLS(TLS);//是否TLS校验,,某些邮箱需要TLS安全校验,同理有SSL校验
- email.setHostName(hostName);
- try{
- email.setFrom(sendMailAddress,sendMailAddress);
- email.setAuthentication(sendMailAddress,mailPassword);
- email.setCharset("utf-8");//解决中文乱码问题
- email.setSubject(mailTitle);//标题
- email.setMsg(mailContent);//内容
- for(inti=0;i<getMailAddress.length;++i){
- email.addTo(getMailAddress[i]);//接收方
- email.send();
- }
- }catch(EmailExceptione){
- //e.printStackTrace();
- }
- }
- publicStringgetHostName(){
- returnhostName;
- }
- publicvoidsetHostName(StringhostName){
- this.hostName=hostName;
- }
- publicStringgetSendMailAddress(){
- returnsendMailAddress;
- }
- publicvoidsetSendMailAddress(StringsendMailAddress){
- this.sendMailAddress=sendMailAddress;
- }
- publicStringgetMailPassword(){
- returnmailPassword;
- }
- publicvoidsetMailPassword(StringmailPassword){
- this.mailPassword=mailPassword;
- }
- publicbooleanisTLS(){
- returnTLS;
- }
- publicvoidsetTLS(booleantls){
- TLS=tls;
- }
- publicString[]getGetMailAddress(){
- returngetMailAddress;
- }
- publicvoidsetGetMailAddress(String[]getMailAddress){
- this.getMailAddress=getMailAddress;
- }
- publicStringgetMailTitle(){
- returnmailTitle;
- }
- publicvoidsetMailTitle(StringmailTitle){
- this.mailTitle=mailTitle;
- }
- publicStringgetMailContent(){
- returnmailContent;
- }
- publicvoidsetMailContent(StringmailContent){
- this.mailContent=mailContent;
- }
- }
分页工具类 SharePager.java
- packagecom.util;
- /**
- *分页工具类
- *
- */
- publicclassSharePager{
- privateinttotalRows;//总行数
- privateintpageSize=20;//每页显示的行数
- privateintcurrentPage;//当前页号
- privateinttotalPages;//总页数
- privateintstartRow;//当前页在数据库中的起始行
- /**
- *默认构造函数
- */
- publicSharePager()
- {
- }
- /**默认每页10行
- *@paramtotalRows
- */
- publicSharePager(inttotalRows)
- {
- this.totalRows=totalRows;
- totalPages=(int)Math.ceil((double)totalRows/(double)pageSize);
- startRow=0;
- }
- /**可自定义每页显示多少页
- *@paramtotalRows
- *@parampageSize
- */
- publicSharePager(inttotalRows,intpageSize)
- {
- this.totalRows=totalRows;
- this.pageSize=pageSize;
- if(this.pageSize<1)
- this.pageSize=1;
- elseif(pageSize>20)
- this.pageSize=20;
- //if(this.pageSize>totalRows){
- //this.pageSize=(int)totalRows;
- //}
- totalPages=(int)Math.ceil((double)totalRows/(double)this.pageSize);
- currentPage=1;
- startRow=0;
- }
- /**
- *跳转到首页
- */
- publicvoidfirst()
- {
- this.currentPage=1;
- this.startRow=0;
- }
- /**
- *跳转到上一页
- */
- publicvoidprevious()
- {
- if(currentPage==1)
- {
- return;
- }
- currentPage--;
- startRow=(currentPage-1)*pageSize;
- }
- /**
- *跳转到下一页
- */
- publicvoidnext()
- {
- if(currentPage<totalPages)
- {
- currentPage++;
- }
- startRow=(currentPage-1)*pageSize;
- }
- /**
- *跳转到尾页
- */
- publicvoidlast()
- {
- this.currentPage=totalPages;
- if(currentPage<1){
- currentPage=1;
- }
- this.startRow=(currentPage-1)*this.pageSize;
- totalPages=(int)Math.ceil((double)totalRows/(double)this.pageSize);
- }
- /**
- *跳转到指定页
- *@paramcurrentPage指定的页
- */
- publicvoidrefresh(intcurrentPage)
- {
- if(currentPage<0)
- {
- first();
- }
- if(currentPage>totalPages)
- {
- last();
- }else{
- this.currentPage=currentPage;
- this.startRow=(currentPage-1)*this.pageSize;
- }
- }
- publicintgetStartRow()
- {
- returnstartRow;
- }
- publicintgetTotalPages()
- {
- returntotalPages;
- }
- publicintgetCurrentPage()
- {
- returncurrentPage;
- }
- publicintgetPageSize()
- {
- returnpageSize;
- }
- publicvoidsetTotalRows(inttotalRows)
- {
- this.totalRows=totalRows;
- }
- publicvoidsetStartRow(intstartRow)
- {
- this.startRow=startRow;
- }
- publicvoidsetTotalPages(inttotalPages)
- {
- this.totalPages=totalPages;
- }
- publicvoidsetCurrentPage(intcurrentPage)
- {
- this.currentPage=currentPage;
- }
- publicvoidsetPageSize(intpageSize)
- {
- this.pageSize=pageSize;
- }
- publicintgetTotalRows()
- {
- returntotalRows;
- }
- }
相关推荐
基本涵盖常用的工具类集合,其中也综合了别人的示例及经验,希望大家可以互通有无,当然也需要持续更新。
常用的Java类集合。
这个包里面包括了Java对数据和日期的处理,以及对图像处理、XML处理和HTML处理等工具类,另外还有其他一些有用类。
J2EE常用工具类汇总 J2EE常用工具类—Value Object工具类 J2EE常用工具类—Json工具 J2EE常用工具类—Jdbc操作 J2EE常用工具类—Hibernate操作 J2EE常用工具类—Cookie操作 ...J2EE常用工具类——字符串工具类
微信小程序——[小工具类]备忘录(截图+源码).zip 微信小程序——[小工具类]备忘录(截图+源码).zip 微信小程序——[小工具类]备忘录(截图+源码).zip 微信小程序——[小工具类]备忘录(截图+源码).zip 微信小...
微信小程序——[小工具类]iOS计算器(截图+源码).zip 微信小程序——[小工具类]iOS计算器(截图+源码).zip 微信小程序——[小工具类]iOS计算器(截图+源码).zip 微信小程序——[小工具类]iOS计算器(截图+源码)....
微信小程序——[小工具类]查拼音(截图+源码).zip 微信小程序——[小工具类]查拼音(截图+源码).zip 微信小程序——[小工具类]查拼音(截图+源码).zip 微信小程序——[小工具类]查拼音(截图+源码).zip 微信小...
微信小程序——[小工具类]步步高字典(截图+源码).zip 微信小程序——[小工具类]步步高字典(截图+源码).zip 微信小程序——[小工具类]步步高字典(截图+源码).zip 微信小程序——[小工具类]步步高字典(截图+...
java 常用工具类(csdn)————程序
Java常用工具类UtilClass,包括StringUtil、FileUtil、ConnectDB、DateUtil、TimeUtil一些可能用到的工具,实现某些特定的功能,,
毕业设计——java覆盖工具
微信小程序——[小工具类]XCX-scaffold-master(截图+源码).zip 微信小程序——[小工具类]XCX-scaffold-master(截图+源码).zip 微信小程序——[小工具类]XCX-scaffold-master(截图+源码).zip 微信小程序——[小...
【Java毕业设计】毕业设计——java覆盖工具
个人开发用的Java常用工具类的集合。 主要用于封装 J2EE 开发过程中的常见操作,避免大量的重复功能代码,提升开发效率,并降低耦合。 ##Guide src/com.cnblogs.honoka.utils.StringUtil.java:字符串处理工具类 src...
java毕业设计——java一个简单的即时通讯工具的设计与开发(源代码+论文).zip java毕业设计——java一个简单的即时通讯工具的设计与开发(源代码+论文).zip java毕业设计——java一个简单的即时通讯工具的设计与开发...
C#常用工具类代码集合Util第二版本(自己工作总结),包括常用工具类,扩展方法工具类,百度地图C#工具类,Echart工具类,Office工具类,Autofac工具类,Web开发常用工具类,Winform开发常用工具类,是自己工作十年...
java常用工具类封装util.rarjava常用工具类封装util.rarjava常用工具类封装util.rarjava常用工具类封装util.rar
Class类工具 \Cookie工具类 \excel读取 工具类\Java如何生成...- CryptoUtils.java\日期工具类 - DateUtil.java\图片处理工具类 - ImageUtils.java\文件相关操作工具类——FileUtils.java\压缩工具类 - ZipUtils.java
XJad——Java反编译工具
java-7_工具类及常用算法