免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1035 | 回复: 0
打印 上一主题 下一主题

几个实用的工具类 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-11-25 11:16 |只看该作者 |倒序浏览

1、自定义格式取当期日期:
public String getMyDate(int type)
{
  String date="";
     Calendar cal = Calendar.getInstance();
     int pm_am=cal.get(Calendar.AM_PM);
     int hour=cal.get(Calendar.HOUR);
     if(pm_am==Calendar.PM) hour+=12;
   
     switch(type)
     {
     case 1: //yyyy-mm-dd
      date+=cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.DATE);
      break;
     case 2: //yyyy-mm-dd hh:mi:ss
      date+=cal.get(Calendar.YEAR)+"-"+(cal.get(Calendar.MONTH)+1)+"-"+cal.get(Calendar.DATE)
       +" "+hour+":"+cal.get(Calendar.MINUTE)+":"+ cal.get(Calendar.SECOND);
      break;
     default:
      date+=null;
     }
      return date;
}
2、计算两时间差(天):
/*
   * Method:输出两日期差,单位(天)
   */
  public long getQuot(String time1, String time2)
  {
   long quot = 0;
   SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
   try {
   Date date1 = ft.parse( time1 );
   Date date2 = ft.parse( time2 );
   quot = date1.getTime() - date2.getTime();
   quot = quot / 1000 / 60 / 60 / 24;
   } catch (ParseException e) {
   e.printStackTrace();
   }
   return quot;
  }
3、转MYSQL的datetime日期类型:
/*
  * Date类型转换为MYSQL DateTime类型
  */
  public static String DateToMySQLDateTimeString(String date)
  {
   final String[] MONTH = {"Jan","Feb","Mar","Apr","May","Jun", "Jul","Aug","Sep","Oct","Nov","Dec",};
   StringBuffer ret = new StringBuffer();
   String dateToString = date.toString(); //like "Sat Dec 17 15:55:16 CST 2005"
   ret.append(dateToString.substring(24,24+4));//append yyyy
   String sMonth = dateToString.substring(4,4+3);
   for(int i=0;i12;i++) { //append mm
    if(sMonth.equalsIgnoreCase(MONTH)) {
     if((i+1)  10)
      ret.append("-0");
     else
      ret.append("-");
     ret.append((i+1));
     break;
    }
   }
   ret.append("-");
   ret.append(dateToString.substring(8,8+2));
   ret.append(" ");
   ret.append(dateToString.substring(11,11+8));
   return ret.toString();
  }
5、MD5加密方法:
// MD5加密方法
public static String change2MD5(String srcString)
{
  MessageDigest md = null;
        try
        {
            md = MessageDigest.getInstance("MD5");
        }
        catch (NoSuchAlgorithmException nsae)
        {
            return "";
        }
        byte[] md5Bytes = md.digest(srcString.getBytes());
        int tmpInt = 0;
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i  md5Bytes.length; i++)
        {
            tmpInt = (int) (md5Bytes & 0xff);
            if (tmpInt  16)
            {
                sb.append("0");
            }
            sb.append(Integer.toHexString(tmpInt));
        }
        return sb.toString();
}
}
6、判断字符是否为0-9和英文字符:
// 判断字符串是否为合法字符
public static boolean isRegStr(String Str)
{
  boolean flag=true;
  Pattern p=null;
  Matcher m=null;
  try
  {
   p = java.util.regex.Pattern.compile("[^0-9A-Za-z]");
   m = p.matcher(Str);
   if(m.find()) flag=false;
  }catch(Exception e)
  {}
  return flag;
}
7、判断邮件格式是否合法:
/*
*判断邮件格式
*/
public static boolean isEmail(String str)
{
  if(str.length()6||str.indexOf('@',0)==-1||str.indexOf('.',0)==-1)
  {
   return false;
  }
  else
  {
   return true;
  }
}
8、替换换行与HTML符号:
//替换换行符号
public static String converLine(String str)
{
  return str.replaceAll("\n", "
");
}

//替换HTML符
public static String converHtmlChar(String str)
{
  str = str.replaceAll("&", "&");
  str = str.replaceAll(" ", " ");
  str = str.replaceAll(", ");
  str = str.replaceAll(">", ">");
  str = str.replaceAll("\"", "&quot");
  return str;
}
9、分割字符的方法:
//字符分割方法
    public static final String[] split(String str, String delims)
    {
        StringTokenizer st = new StringTokenizer(str, delims);
        ArrayList list = new ArrayList();
        for(; st.hasMoreTokens(); list.add(st.nextToken()));
        return (String[])list.toArray(new String[list.size()]);
    }

10、JSP与Servlet处理字符乱码方式:
// 用于读数据库时由iso8859-1变为GBK
public static String GBKConverter(String s_string){
  try{
  String des = new String(s_string.getBytes("iso8859-1"),"gb2312");
  return des;
  }
  catch(Exception ex){
  String des="";
  return des;
  }
}

// 用于处理页内生成的中文数据在写入数据库时的处理,由GBK变为iso8859-1
public static String ISOConverter(String s_string){
  try{
  String des = new String(s_string.getBytes("gb2312"),"iso8859-1");
  return des;
  }
  catch(Exception ex){
  String des = "";
  return des;
  }
}
11、从数据源获取connection:
//从数据库源获取数据连接
public static Connection getConnectionFromDs()
{
  Connection con=null;
  DataSource ds=null;
  Context context=null;
  
  try {
   //1连接到JNDI服务器
   context=new InitialContext();
   //2获取数据库源
   ds=(DataSource)context.lookup("java:comp/env/jdbc/mysql-local");
   con=ds.getConnection();
   System.out.println("已获取数据库连接池!!");
  } catch (NamingException e) {
   e.printStackTrace();
  } catch (SQLException e) {
   e.printStackTrace();
  }
  return con;
}
12、生成4位图片验证码:
public class CreateValidateCode extends HttpServlet {
// 生成随机种子
Random random = new Random();

public void doGet(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  processRequest(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
   throws ServletException, IOException {
  processRequest(request, response);
}
protected void processRequest(HttpServletRequest request,
   HttpServletResponse response) throws ServletException, IOException {
  response.setContentType("image/jpeg");
  response.setHeader("Pragma", "No-cache");
  response.setHeader("Cache-Control", "no-cache");
  response.setDateHeader("Expires", 0);
  HttpSession session = request.getSession(true);
  // 在内存中创建图象
  int width = 50, height = 25;
  BufferedImage image = new BufferedImage(width, height,
    BufferedImage.TYPE_INT_RGB);
  // 获取图形上下文
  Graphics g = image.getGraphics();
  // 设定背景色
  g.setColor(getRandColor(200, 250));
  g.fillRect(0, 0, width, height);
  // 设定字体
  g.setFont(new Font("Georgia", Font.BOLD, 16));
  // 画边框
  // g.setColor(getRandColor(0,0));
  // g.drawRect(0,0,width-1,height-1);
  // 随机产生155条干扰线,使图象中的认证码不易被其它程序探测到
  g.setColor(getRandColor(160, 220));
  for (int i = 0; i  155; i++) {
   int x = random.nextInt(width);
   int y = random.nextInt(height);
   int xl = random.nextInt(12);
   int yl = random.nextInt(12);
   g.drawLine(x, y, x + xl, y + yl);
  }
   
  // 取随机产生的认证码(4位数字)
  String sRand = "";
  for (int i = 0; i  4; i++) {
   String rand = createRandStr();
   sRand += rand;
   // 将认证码显示到图象中
   g.setColor(new Color(40 + random.nextInt(110), 40 + random
     .nextInt(110), 40 + random.nextInt(110)));
   // 调用函数出来的颜色相同,可能是因为种子太接近,所以只能直接生成
   g.drawString(rand, 10 * i + 3, 18);
  }
  // 将认证码存入SESSION
  session.setAttribute("rand", sRand);
  // 图象生效
  g.dispose();
  ServletOutputStream responseOutputStream = response.getOutputStream();
  // 输出图象到页面
  ImageIO.write(image, "JPEG", responseOutputStream);
  // 以下关闭输入流!
  responseOutputStream.flush();
  responseOutputStream.close();
}
public String createRandStr()
{
  //Random random = new Random();
  String str="";
  String[] arr={"0","1","2","3","4","5","6","7","8","9","a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
   
  //for(int i=0;i
  //{
   int rand=random.nextInt(61);
   str=arr[rand];
  //}
  return str;
}

Color getRandColor(int fc, int bc) {
  // 给定范围获得随机颜色
  Random random = new Random();
  if (fc > 255)
   fc = 255;
  if (bc > 255)
   bc = 255;
  int r = fc + random.nextInt(bc - fc);
  int g = fc + random.nextInt(bc - fc);
  int b = fc + random.nextInt(bc - fc);
  return new Color(r, g, b);
}
}


本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u1/52135/showart_1664533.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP