时间工具类:
package com.login.util; import java.text.SimpleDateFormat; import java.util.Calendar; import java.util.Date; public class DateTool { /** * 返回当前时间字符串 * * @return String */ public static String getDateTimeString() { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 采用默认的格式 return sdf.format(new Date()); } /** * 将字符串转成时间 * * @param DateString * @return */ public static Date getDate(String DateString) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 采用默认的格式 try { return sdf.parse(DateString); } catch (Exception e) { return null; } } /** * 返回日期转换成字符串yyyyMMdd * * @param date * --日期 * @return String */ public static String getDateString1(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd"); // 采用年月日 return sdf.format(date); } /** * 精确到微秒 * * @param DateString * @return */ public static Date getDate1(String DateString) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // 采用默认的格式 try { return sdf.parse(DateString); } catch (Exception e) { return null; } } /** * 返回系统日期时间字符串 * * @param datetimeType * --时间格式(如yyyyMMddHHmmss) * @return String */ public static String getDateTimeString(String datetimeType) { SimpleDateFormat sdf = new SimpleDateFormat(datetimeType); return sdf.format(new Date()); } /** * 返回系统时间字符串 * * @param dateTime * --日期时间 * @return String */ public static String getDateTimeString(Date dateTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 采用默认的格式 return sdf.format(dateTime); } /** * 返回系统时间字符串精确到微秒 * * @param dateTime * --日期时间 * @return String */ public static String getDateTimeString1(Date dateTime) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS"); // 采用默认的格式 return sdf.format(dateTime); } /** * 返回系统日期字符串 * * @param date * --日期 * @return String */ public static String getDateString(Date date) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); // 采用默认的格式 return sdf.format(date); } /** * 返回系统时间字符串 * * @param date * --时间 * @param datetimeType * --时间格式(如yyyyMMddHHmmss) * @return String */ public static String getDateTimeString(Date date, String datetimeType) { SimpleDateFormat sdf = new SimpleDateFormat(datetimeType); return sdf.format(date); } /** * 一个日期加上小时后变成新的时间 * * @param date * 日期 * @param minute * 小时 * @return 返回相加后的日期 */ public static java.util.Date addDate(Date date, long minute) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTimeInMillis(getMillis(date) + minute * 60 * 1000); return c.getTime(); } /** * 一个日期减去分钟后变成新的时间 * * @param date * 日期 * @param hour * 分种 * @return 返回相加后的日期 */ public static java.util.Date subDate(Date date, long minute) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTimeInMillis(getMillis(date) - minute * 60 * 1000); return c.getTime(); } /** * 一个日期减去分钟后变成新的时间 * * @param date * 日期 * @param hour * 分种 * @return 返回相加后的日期 */ public static java.util.Date subDate1(Date date, int second) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTimeInMillis(getMillis(date) - second * 1000); return c.getTime(); } /** * 返回毫秒 * * @param date * 日期 * @return 返回毫秒 */ public static long getMillis(Date date) { java.util.Calendar c = java.util.Calendar.getInstance(); c.setTime(date); return c.getTimeInMillis(); } /** * 两个日期之间相差几秒 * * @param beginTime * @param endTime * @return */ public static int subDate(String beginTime, String endTime) { Date begin = getDate(beginTime); Date end = getDate(endTime); return (int) (getMillis(end) - getMillis(begin) / 1000); } /** * 将时间格式的字符串转换成时间类型 * * @param datetimeString * --时间格式的字符串 * @return */ public static Date parseStringToDate(String datetimeString) { SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); // 采用默认的格式 Date dt = null; try { dt = sdf.parse(datetimeString); } catch (Exception e) { } return dt; } /** * 将时间格式的字符串转换成时间类型 * * @param datetimeString * --时间格式的字符串 * @param datetimeType * --时间格式 * @return */ public static Date parseStringToDate(String datetimeString, String datetimeType) { SimpleDateFormat sdf = new SimpleDateFormat(datetimeType); Date dt = null; try { dt = sdf.parse(datetimeString); } catch (Exception e) { } return dt; } /** * 获得某一日期的前一天 * * @param date * @return Date */ public static Date getPreviousDate(Date date) { Calendar calendar = Calendar.getInstance(); calendar.setTime(date); int day = calendar.get(Calendar.DATE); calendar.set(Calendar.DATE, day - 1); return new Date(calendar.getTime().getTime()); } }
文件工具类:
package com.login.util; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.PrintWriter; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; public class FileTool { /** * 下载文件 * @param filePath --文件完整路径 * @param response */ public static void downloadFile( String filePath, javax.servlet.http.HttpServletResponse response) { String fileName = ""; try { if(filePath.lastIndexOf("/") > 0) { fileName = new String(filePath.substring(filePath.lastIndexOf("/")+1, filePath.length()).getBytes("GB2312"), "ISO8859_1"); }else if(filePath.lastIndexOf("\\") > 0) { fileName = new String(filePath.substring(filePath.lastIndexOf("\\")+1, filePath.length()).getBytes("GB2312"), "ISO8859_1"); } }catch(Exception e) {} //打开指定文件的流信息 FileInputStream fs = null; try { fs = new FileInputStream(new File(filePath)); }catch(FileNotFoundException e) { e.printStackTrace(); return; } //设置响应头和保存文件名 response.setContentType("APPLICATION/OCTET-STREAM"); response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); //写出流信息 int b = 0; try { PrintWriter out = response.getWriter(); while((b=fs.read())!=-1) { out.write(b); } fs.close(); out.close(); }catch(Exception e) { e.printStackTrace(); } } /** * @param * inputFileName 想要压缩的文件夹 * * @param * targetFile 生成文件存放的位置 */ public static void Zip(String targetFile,String inputFileName)throws Exception { Zip(targetFile,new File(inputFileName)); } public static void Zip(String zipFileName,File inputFile)throws Exception { ZipOutputStream out=new ZipOutputStream(new FileOutputStream(zipFileName)); Zip(out,inputFile,""); out.close(); } /** * * @param out 要压缩到哪个目录下 * @param f 要压缩的文件夹的路径 * @param base 为顶层目录 * @throws Exception */ public static void Zip(ZipOutputStream out,File f,String base)throws Exception{ if(f.isDirectory()) { //获取文件夹里面的所有数据 File[] ary_f=f.listFiles(); out.putNextEntry(new ZipEntry(base+"/")); base=base.length()==0?"":base+"/"; for(int i=0;i<ary_f.length;i++) { Zip(out,ary_f[i],base+ary_f[i].getName()); } }else { out.putNextEntry(new ZipEntry(base)); FileInputStream in=new FileInputStream(f); int b; while((b=in.read())!=-1) { out.write(b); } in.close(); } } /** * 复制单个文件 * @param oldPathFile 准备复制的文件源 * @param newPathFile 拷贝到新绝对路径带文件名 * @return */ public static void copyFile(String oldPathFile, String newPathFile) { try { int bytesum = 0; int byteread = 0; File oldfile = new File(oldPathFile); if (oldfile.exists()) { //文件存在时 InputStream inStream = new FileInputStream(oldPathFile); //读入原文件 FileOutputStream fs = new FileOutputStream(newPathFile); byte[] buffer = new byte[1444]; while((byteread = inStream.read(buffer)) != -1){ bytesum += byteread; //字节数 文件大小 fs.write(buffer, 0, byteread); } inStream.close(); } }catch (Exception e) { e.printStackTrace(); } } /** * 新建目录 * @param folderPath 目录 * @return 返回目录创建后的路径 */ public static void createFolder(String folderPath) { String txt = folderPath; try { File myFilePath = new File(txt); txt = folderPath; if (!myFilePath.exists()) { myFilePath.mkdir(); } } catch (Exception e) { e.printStackTrace(); } } /** * 删除空目录 * @param folderPath 目录 * @return 返回目录创建后的路径 */ public static void deleteFolder(String folderPath) { String txt = folderPath; try { File myFilePath = new File(txt); txt = folderPath; if (myFilePath.exists()) { myFilePath.delete(); } } catch (Exception e) { e.printStackTrace(); } } /** * 将文件移动新的文件夹 * @param sourceFile * @param targetPath * @return --文件名 */ public static String moveFile(String sourceFile,String targetPath){ try{ File oldFile=new File(sourceFile); //new一个新文件夹 File fnewpath = new File(targetPath); //判断文件夹是否存在 if(!fnewpath.exists()) fnewpath.mkdirs(); //将文件移到新文件里 String oldFileName=oldFile.getName(); String []names=oldFileName.split("\\."); String name=names[0]; String suffix=""; if(names.length>1){ suffix="."+names[1]; } for(int i=0;;i++){ File file=new File(targetPath +name+String.valueOf(i)+suffix); if(!file.exists()){ oldFileName=targetPath +name+String.valueOf(i)+suffix; break; } } File fnew = new File(oldFileName); oldFile.renameTo(fnew); return oldFileName; }catch(Exception e){ e.printStackTrace(); return ""; } } /** * 删除文件夹及文件夹下的文件 * @param folderPath 文件夹完整绝对路径 */ public static void delFolder(String folderPath) { try { delAllFile(folderPath); //删除完里面所有内容 String filePath = folderPath; filePath = filePath.toString(); java.io.File myFilePath = new java.io.File(filePath); myFilePath.delete(); //删除空文件夹 } catch (Exception e) { e.printStackTrace(); } } /** * 删除文件夹下的所有文件 * @param path 文件夹完整绝对路径 */ public static boolean delAllFile(String path) { boolean flag = false; File file = new File(path); if (!file.exists()) { return flag; } if (!file.isDirectory()) { return flag; } String[] tempList = file.list(); File temp = null; for (int i = 0; i < tempList.length; i++) { if (path.endsWith(File.separator)) { temp = new File(path + tempList[i]); } else { temp = new File(path + File.separator + tempList[i]); } if (temp.isFile()) { temp.delete(); } if (temp.isDirectory()) { delAllFile(path + "/" + tempList[i]);//先删除文件夹里面的文件 delFolder(path + "/" + tempList[i]);//再删除空文件夹 flag = true; } } return flag; } }
对于properties文件的工厂类,文件存放src目录下:
package com.login.util; import java.io.InputStream; import java.util.Properties; import org.apache.log4j.Logger; /** * 读取资源文件 * @author zhongqian */ public class PropertyFactory { static Logger logger = Logger.getLogger(PropertyFactory.class); public static Properties getIndexProperties(){ return getProperties("index.properties"); } public static Properties getWebServieProperties(){ return getProperties("webservice.properties"); } public static Properties getHqlProperties(){ return getProperties("hql.properties"); } public static Properties getPageUrlProperties(){ return getProperties("pageurl.properties"); } public static Properties getProperties(String propFile){ Properties p = null; try{ InputStream in = PropertyFactory.class.getClassLoader().getResourceAsStream(propFile); p = new Properties(); p.load(in); }catch(Exception e){ logger.error("Can not load "+propFile + " properties file."); } return p; } public static void main(String[] args) { System.out.println(getIndexProperties().get("name")); } }
其它有用方法:
package com.login.util; import java.io.FileInputStream; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.lang.reflect.Method; import java.net.URLEncoder; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Collection; import java.util.Random; import java.util.UUID; import com.sun.org.apache.xerces.internal.impl.dv.util.Base64; public class Tools { /** * 判断字符串是否为数字 */ public static boolean isNumber(String number){ try{ Integer.parseInt(number); return true; }catch(Exception e){ return false; } } /** * 将字符串转换成数字,当字符串不为数字时返回0 */ public static int parseToInt(String number){ int value; if(isNumber(number)){ value = Integer.parseInt(number); }else{ value = 0; } return value; } /** * 生成UUID * @return String */ public static String getUUID() { return UUID.randomUUID().toString().replaceAll("-", ""); } /** * 加密字符串 * @param sStr --要加密的字符串 * @param securityType --MD5或SHA * @return String */ public static String getSecurityString(String sStr, String securityType) { String returnStr = ""; MessageDigest md = null; try { md = MessageDigest.getInstance(securityType); md.update(sStr.getBytes()); returnStr = new String(Base64.encode(md.digest())); }catch(Exception e) {} if(returnStr.equals("")) { returnStr = sStr; } return returnStr.trim(); } /** * 向页面输出文本内容 * @param str * @param reponse */ public static void printWriter(String str, javax.servlet.http.HttpServletResponse response) { response.setContentType("text/html;charset=UTF-8"); java.io.PrintWriter out; try { out = response.getWriter(); out.print(str); }catch(java.io.IOException e) { e.printStackTrace(); } } /** * 输入图片 * @param filePath--数据来源 * @param response */ public static void showPhoto(String filePath, javax.servlet.http.HttpServletResponse response) { //打开指定文件的流信息 /**FileInputStream fs = null; File dlfile=null; try { dlfile=new File(filePath); fs = new FileInputStream(dlfile); }catch(FileNotFoundException e) { e.printStackTrace(); return; } //设置响应头和保存文件名 //response.setContentType("text/tiff"); 显示传真 response.setContentType("image/jpg"); response.setHeader("Content-Length",String.valueOf(dlfile.length())); //写出流信息 int b = 0; try { PrintWriter out = response.getWriter(); while((b=fs.read())!=-1) { out.write(b); } fs.close(); out.close(); println("文件下载完毕."); }catch(Exception e) { e.printStackTrace(); println("下载文件失败!"); }**/ try{ FileInputStream hFile = new FileInputStream(filePath); // 以byte流的方式打开文件 d:\1.gif int i=hFile.available(); //得到文件大小 byte data[]=new byte[i]; hFile.read(data); //读数据 hFile.close(); response.setContentType("image/*"); //设置返回的文件类型 OutputStream toClient=response.getOutputStream(); //得到向客户端输出二进制数据的对象 toClient.write(data); //输出数据 toClient.close(); } catch(IOException e) //错误处理 { //PrintWriter toClient = (PrintWriter)response.getWriter(); //得到向客户端输出文本的对象 //response.setContentType("text/html;charset=gb2312"); //toClient.write("无法打开图片!"); //toClient.close(); e.printStackTrace(); } } /** * 取得随机数 字符串 * @param num --指定字符个数 * @return String */ public static String getRandomNum(int num) { String rStr = ""; Random rdm = new Random(); rStr = String.valueOf(Math.abs(rdm.nextInt())); if(num > rStr.length())return rStr; return rStr.substring(0, num); } /** * 转换字符串为URL编码 * @param str * @return String */ public static String getUrlString(String str) { if(str == null || str.equals(""))return ""; String encodeStr = ""; try { URLEncoder.encode(str, "GBK"); }catch(UnsupportedEncodingException e) {} return encodeStr; } /** * 格式化字符串为中文 * @param str * @return String */ public static String getZhString(String str) { String outString = ""; try { outString = new String(str.getBytes("GB2312"), "ISO8859_1"); }catch(Exception e) {} return outString; } /** * 根据对象实例返回这个实例的所有get方法返回的数据类型、字段名、返回值 * @param instance * @return Collection */ public static Collection<Object> getMethodInfo(Object instance) { Collection<Object> methodInfo = new ArrayList<Object>(); Object[] fv = null; Method[] methods = instance.getClass().getDeclaredMethods(); for(int i=0;i<methods.length;i++) { String methodName = methods[i].getName(); if(methodName.startsWith("get")) { Object[] args = null; Object returnValue = null; try { returnValue = methods[i].invoke(instance, args); if(returnValue != null && !returnValue.equals("")) { //获取实际字段名 String fieldName = methodName.substring(3,methodName.length()); String oneWord = fieldName.substring(0,1).toLowerCase(); String endAllWord = fieldName.substring(1, fieldName.length()); fieldName = oneWord + endAllWord; fv = new Object[3]; fv[0] = methods[i].getReturnType(); //保存返回类型 fv[1] = fieldName; //保存字段名 fv[2] = returnValue; //保存返回值 methodInfo.add(fv); } }catch(Exception e) { e.printStackTrace(); } } } return methodInfo; } }
原文:http://blog.csdn.net/moneyzhong/article/details/23258693