import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.math.BigDecimal; import java.net.Inet6Address; import java.net.UnknownHostException; import java.text.DateFormat; import java.text.DecimalFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Calendar; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.upload.FormFile; import com.popedom.dyhx.config.Config; /** * 2009年元月 * 工具类,通用方法 * @author sunyong * */ public class Tools {
/** *取得当前时间 * @return */ public static Date nowDate(String format){ SimpleDateFormat sdf = new SimpleDateFormat(format); String d=sdf.format(new Date()); return java.sql.Date.valueOf(d); } /** *取得当前时间 * @return */ public static Date nowUtilDate(String format){ SimpleDateFormat sdf = new SimpleDateFormat(format); String d=sdf.format(new Date()); try { return DateFormat.getDateInstance().parse(d); } catch (ParseException e) { return new Date(); } } /** *取得当前时间 * @return */ public static String nowDateTime(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); String d=sdf.format(new Date()); return d; } /** *取得当前时间 * @return */ public static String nowDateByyyyMMdd(){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String d=sdf.format(new Date()); d=d.substring(0, d.indexOf("-"))+d.substring(d.indexOf("-")+1); d=d.substring(0, d.indexOf("-"))+d.substring(d.indexOf("-")+1); return d; } public static String EnglishToChinese(String s){ String str=""; try { str=new String(s.getBytes("ISO-8859-1"),"GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return str; } public static String Utf8(String s){ String str=""; try { str=new String(s.getBytes("ISO-8859-1"),"UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return str; } public static String GBKToISO88591(String s){ String str=""; try { str=new String(s.getBytes("GBK"),"ISO-8859-1"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return str; } /** * 判断一个字符串是否是乱码,如果是则转码 * @param str * @return String str */ public static String checkStrIsFail(String str){ if(str==null){ return ""; } if(isGBK(str)){ try { return new String(str.getBytes("ISO-8859-1"),"GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return ""; } }else{ return str; } } /** * 判断是否是乱码 * @param str * @return */ public static boolean isGBK(String str){ try { str = new String(str.getBytes("ISO-8859-1"), "GBK"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } char ws[] = new char[]{'"', '?' , '\'' , '&'}; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); //System.out.println((int)c); for(int j = 0; j < ws.length; j++){ char v = ws[j]; //System.out.println("要验证的字符是: |" + v + "| != |" + c + "|"); if (c == v){ return false; } } if((int)c == 0xfffd) { return false; } }return true; } /** * 取得本机IP * @param req * @return */ public static String nowIp(HttpServletRequest req){ return req.getRemoteAddr(); } /** * 时间格式转换 * @param date * @return */ public static String formatDate(Date date){ SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); String d=sdf.format(date); return d; } /** * 时间格式转换(yyyyMMdd 到 yyyy-MM-dd) * @param date * @param format * @return */ public static String formatDate_s(String date,String format){ String da=date.substring(0,4)+"-"+date.substring(4,6)+"-"+date.substring(6); SimpleDateFormat sdf = new SimpleDateFormat(format); String d=""; d = sdf.format(java.sql.Date.valueOf(da)); return d; } /** *弹出提示框(带转向的) * @param msg 提示内容 * @param toUrl 转向路径 * @return */ public static String Alert_Redirect(String msg, String toUrl) { String str = ""; str = "<script language=javascript>"; str = str + "<!--\n"; str = str + "alert(\"" + msg + "\")\n"; if (!(toUrl.equals(""))) str = str + "location.href=\"" + toUrl + "\"\n"; str = str + "-->\n"; str = str + "</script>\n"; return str; } /** *弹出提示框(带转向与JS函数的) * @param msg 提示内容 * @param toUrl 转向路径 * @return */ public static String Alert_Redirect(String msg, String toUrl,String js) { String str = ""; str = "<script language=javascript>\n"; if(!("".equals(msg))){ str = str + "alert(\"" + msg + "\");\n"; } if (!(toUrl.equals(""))) str = str + "location.href=\"" + toUrl + "\"\n"; str = str+js; str = str + "</script>\n"; return str; } /** * 弹出提示框(确定后返回) * @param msg 提示内容 * @return */ public static String Alert_Back(String msg) { String str = ""; str = "<script language=javascript>\n"; str = str + "<!--\n"; str = str + "alert(\"" + msg + "\")\n"; str = str + "history.back()\n"; str = str + "-->\n"; str = str + "</script>\n"; return str; } /** * 弹出提示框 * @param msg 提示内容 * @return */ public static String Alert(String msg) { String str = ""; str = "<script language=javascript>\n"; str = str + "<!--\n"; str = str + "alert(\"" + msg + "\")\n"; str = str + "-->\n"; str = str + "</script>\n"; return str; } /** * 文件上传(应用与Struts1.2) * @param request * @param response * @param formFile * @param locationPath * @return * @throws IOException */ public static String upload(HttpServletRequest request, HttpServletResponse response,FormFile formFile,String locationPath) throws IOException { @SuppressWarnings("unused") int filesize = formFile.getFileSize(); if(filesize==0){ try { response.getWriter().print(Alert_Redirect("文件大小不能为0!",locationPath)); return null; } catch (IOException e) { e.printStackTrace(); } } String file_path = request.getSession().getServletContext().getRealPath("/WEB-INF/upload_xml").replaceAll("%20", " ");//上传到服务器的路径 File file = new File(file_path); if(!file.exists()){ file.mkdir(); } String realPath=file_path+"\\"+formFile.getFileName(); File f1 = new File(realPath); FileOutputStream fos=null; response.setCharacterEncoding("GBK"); try { fos = new FileOutputStream(f1); fos.write(formFile.getFileData()); fos.flush(); fos.close(); return realPath; } catch (FileNotFoundException e) { response.getWriter().print(Alert_Redirect("文件未找到,请确认文件是否存在!", locationPath)); e.printStackTrace(); return null; }catch(IOException e){ e.printStackTrace(); }return null; } /** * 文件下载 * @param filepath 路径 * @param filename 文件名 * @param request * @param response */ public static boolean downFile(String filepath ,String filename,HttpServletRequest request, HttpServletResponse response) { try { File f = new File(filepath.replaceAll("%20", " ")); if(!f.exists()){ response.setCharacterEncoding("GBK"); response.getWriter().print(Tools.Alert_Back("文件路径不正确或文件不存在!")); return false; } InputStream is = new FileInputStream(f); OutputStream os=response.getOutputStream();; BufferedInputStream bis = new BufferedInputStream(is); BufferedOutputStream bos =new BufferedOutputStream(os); response.reset(); response.setCharacterEncoding("GBK"); response.setContentType("text/html;charset=GBK");//设置charset,文件的字符编码 response.setContentType("application/x-msdownload");//纯下载 /*pdf response.setContentType("application/pdf");// word response.setContentType("application/msword");*/ response.setHeader("Content-Disposition", "attachment;filename="+filename); int bytesRead = 0; byte[] buffer = new byte[(int)f.length()]; while ((bytesRead = bis.read(buffer)) != -1) { bos.write(buffer, 0, bytesRead);//buffer read } bos.flush(); bis.close(); bos.close(); is.close(); os.close(); return true; } catch (FileNotFoundException e) { e.printStackTrace(); return false; }catch(IOException e){ e.printStackTrace(); return false; } } //对对象进行四舍五入. public static String sswr_comm(Object value,String point){ DecimalFormat df = new DecimalFormat("#0."+point); String str=""; if(value == null || "".equals(value)){ new Throwable( "不能传空值!"); } try{ if(value instanceof String) { str = df.format(Double.parseDouble(value.toString())); }else if(value instanceof Double){ str = df.format(value); } }catch(Exception e){ e.printStackTrace(); } return str; } /** * 四舍五入 * @param value * @return */ public static String sswr(Double value,String point){ DecimalFormat df = new DecimalFormat("#0."+point); String str = df.format(value); return str; } /** * 四舍五入 * @param value * @return */ public static double sswr_d(Double value,String point){ DecimalFormat df = new DecimalFormat("#0."+point); String str = df.format(value); return Double.parseDouble(str); } /** * 四舍五入 * @param value * @return */ public static String sswr(String value,String point){ DecimalFormat df = new DecimalFormat("#0."+point); String str = df.format(Double.parseDouble(value)); return str; } /** * null 或 "" 转换成返回一个"" 否则将结果四舍五入返回 * @param obj * @return */ public static String nullTonbsp_sswr(Object obj,String point){ if(obj==null || "".equals(obj)){ return ""; }else{ return sswr(obj.toString(),point); } } public static String FormatDouble(Object obj){ if(obj==null){ obj=0.0; } DecimalFormat decimalFormat = new DecimalFormat("0.00"); String str = decimalFormat.format(obj); return str; } public static BigDecimal FormateDecimal(Double d){ return BigDecimal.valueOf(d); } public static Double parseDouble(String s){ if(s==null || "".equals(s)){ return 0d; }else{ return Double.parseDouble(s); } } public static Long parseLong(Object s){ if(s==null || "".equals(s)){ return 0L; }else{ return Long.parseLong(s+""); } } /** * 得到一个文件夹下的所有文件并存入到Map容器中 * @param filepath 文件夹路径 * @param pathMap Map容器 * @return Map<Integer,String> * @throws Exception */ public static Map<Integer, String> readfile(String filepath, Map<Integer, String> pathMap) throws Exception { if (pathMap == null) { pathMap = new HashMap<Integer, String>(); } File file = new File(filepath); // 文件 if (!file.isDirectory()) { pathMap.put(pathMap.size(), file.getPath()); } else if (file.isDirectory()) { // 如果是目录, 遍历所有子目录取出所有文件名 String[] filelist = file.list(); for (int i = 0; i < filelist.length; i++) { File readfile = new File(filepath + "/" + filelist[i]); if (!readfile.isDirectory()) { //System.out.println(readfile.getName()); if(readfile.getName().lastIndexOf(".")!=-1){ String endWith = readfile.getName().substring(readfile.getName().lastIndexOf(".")); //if(".xls".equalsIgnoreCase(endWith)){ pathMap.put(pathMap.size(), readfile.getPath()); //} } } else if (readfile.isDirectory()) { // 子目录的目录 readfile(filepath + "/" + filelist[i], pathMap); } } } return pathMap; } /** * Map转换为List * @param pathMap * @return */ @SuppressWarnings("unchecked") public static List<String> mapToList(Map<Integer,String> pathMap){ List pathList =null; if(pathMap!=null){ pathList = new ArrayList(); } for(int i=0;i<pathMap.size();i++){ pathList.add(pathMap.get(i)); }return pathList; } /** * 求两个时间相差的分钟数 * @param date1 如:yyyy-MM-dd HH:mm * @param date2 如:yyyy-MM-dd HH:mm * @return number */ public static Long getDays_hour(String stratdate, String enddate) { if (stratdate == null || stratdate.equals("")) return 0L; if (enddate == null || enddate.equals("")) return 0L; // 转换为标准时间 SimpleDateFormat myFormatter = new SimpleDateFormat("yyyy-MM-dd HH:mm"); java.util.Date date = null; java.util.Date mydate = null; try { date = myFormatter.parse(stratdate); mydate = myFormatter.parse(enddate); } catch (Exception e) { e.printStackTrace(); } return (mydate.getTime()-date.getTime()) / (long)(60 * 1000); //计算分钟 } /** * 获得指定时间加指定分钟后的时间 * @param d 指定时间 * @param minute 分钟 * @return */ public static Date getDate(Date d,int minute){ Calendar now = Calendar.getInstance(); now.setTime(d); now.set(Calendar.MINUTE, now.get(Calendar.MINUTE) + minute); //SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm"); return now.getTime(); } }