欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

一些工具

程序员文章站 2022-05-27 16:22:31
...

JAVA生成随机验证码

一、要求生成随机八位的验证码

二、4个数字在前,4个字母在后

三、字母包含大小写

package operator;

import java.util.Random;

public class day01 {
    public static void main(String[] args) {
        //大小写字母合计为52位
        char[] xianyufanshen = new char[52];
        //index表示要操作的那个索引
        int index = 0;
        for (int i = 'A'; i <= 'Z'; i++) {
            //i 表示 ‘A’ ~ ‘Z’ 之间的字符所对应的数字
            xianyufanshen[index] = (char) i;
            index++;
        }
        //当循环结束之后,数组中存了A-Z
        for (int i = 'a'; i <= 'z'; i++) {
            //i 表示 ‘a’ ~ ‘z’ 之间的字符所对应的数字
            xianyufanshen[index] = (char) i;
            index++;
        }
        Random r = new Random();
        //随机生成四个0-9之间的随机数。
        for (int i = 0; i < 4; i++) {
            int randomNumber = r.nextInt(10);
            System.out.print(randomNumber);
        }
        //随机生成4个大小写字母
        for (int i = 0; i < 4; i++) {
            int randomIndex = r.nextInt(xianyufanshen.length);
            char randomChar = xianyufanshen[randomIndex];
            System.out.print(randomChar);
        }


    }
}

验证数组是否为空

public static boolean arrayValid(Object[] objects) {
	if (objects != null && objects.length > 0) {
		return true;
	} else {
		return false;
	}
}

验证list是否为空

public boolean listValid(List list) {
	if (list != null && list.size() > 0) {
		return true;
	} else {
		return false;
	}
}
  

获得年龄

  public int age(String dateStart, String dateEnd) throws Exception{
	  int yearStart = Integer.parseInt(dateStart.substring(0,4));
	  int yearEnd = Integer.parseInt(dateEnd.substring(0,4));
	  return yearEnd-yearStart;
  }

是否为奇数

  public boolean isOdd(int i){
	  if(i%2==0){
		  return false;
	  }else{
		  return true;
	  }
  }

返回固定长度串,空白地方用空格填充

  public String fixSpaceStr(String str,int len){
	  StringBuffer sBuf = new StringBuffer();
	  try{
		  if(str.length()>len){
			  return str;
		  }else{
			  sBuf.append(str);
			  for(int i=0;i<(len-str.length());i++){
				  sBuf.append(" ");
			  }
			  return sBuf.toString();
		  }
	  }catch(Exception e){
		  return str;
	  }
  }
  public String fixSpaceStr(int number,int len){
	  return fixSpaceStr(String.valueOf(number),len);
  }
  

前缀空格

  public String prefixSpaceStr(String str,int len){
	  StringBuffer sBuf = new StringBuffer();
	  try{
		  if(str.length()>len){
			  return str;
		  }else{
			  for(int i=0;i<(len-str.length());i++){
				  sBuf.append(" ");
			  }
			  sBuf.append(str);
			  return sBuf.toString();
		  }
	  }catch(Exception e){
		  return str;
	  }
  }

截取字符,如果超过长度,截取并加省略号

  public String suspensionStr(String str,int len){
	  try{
		  str = str.substring(0,len) + "...";
	  }catch(Exception e){
		  return str;
	  }
	  return str;
  }

url get方式传递参数

  public static String joinUrlParameter(List<String> sList){
	  StringBuffer sBuf = new StringBuffer();
	  for(Iterator it = sList.iterator(); it.hasNext();){
		  sBuf.append("&").append(it.next()).append("=").append(it.next());
	  }
	  return sBuf.substring(1, sBuf.length());	//去掉第一个&符号
  }
  

字符串返回分割后的数组

  static public String[] splitStr(String str,String SplitFlag){
    int i =0;
    try{
      StringTokenizer st = new StringTokenizer(str, SplitFlag);
      String tokens[] = new String[st.countTokens()];  
      while (st.hasMoreElements()) {
        tokens[i] = st.nextToken();
        i++;
      }
      return tokens;
    }catch(Exception e){
      return null;
    }
  }

阶梯函数,例如,a,b,c 返回 a; a,b; a,b,c

  static public String[] splitStair(String str,String SplitFlag){
	  try{
		  String[] _temp = splitStr(str, SplitFlag);
		  for(int i=1;i<_temp.length;i++){
			  _temp[i] = _temp[i-1]+SplitFlag+_temp[i];
		  }
		  return _temp;
	  }catch(Exception e){
		  return null;
	  }
  }

将数组合并为一个字符串

输入参数:String aStr 要合并数组

输入参数:String SplitFlag 设置分割字符

输出参数:String 要合并数组

  static public String joinStr(String[] aStr,String SplitFlag){
    StringBuffer sBuffer = new StringBuffer();
    if (aStr != null){
      for (int i=0;i<aStr.length;i++){
        sBuffer.append(aStr[i]).append(SplitFlag);
      }
      sBuffer.delete(sBuffer.length() - 1, sBuffer.length()); //去掉最后的分隔符 SplitFlag
    }else{
      sBuffer = sBuffer.append("");
    }
    return sBuffer.toString();
  }

将数组合并为一个字符串

String sPrefix 数组元素加的前缀

String sSuffix 数组元素加的后缀

String SplitFlag 设置分割字符

String 合并后的字符串

  static public String joinStr(String[] aStr,String sPrefix,String sSuffix,String SplitFlag){
    StringBuffer sBuffer = new StringBuffer();
    if (aStr != null){
      for (int i=0;i<aStr.length;i++){
        sBuffer.append(sPrefix).append(aStr[i]).append(sSuffix).append(SplitFlag);
      }
      sBuffer.delete(sBuffer.length() - SplitFlag.length(), sBuffer.length()); //去掉最后的分隔符 SplitFlag
    }else{
      sBuffer = sBuffer.append("");
    }
    return sBuffer.toString();
  }
  

数组返回用于in查询的串 ‘x’,‘y’

  static public String joinInStr(String[] aStr){
	  StringBuffer sBuffer = new StringBuffer();
	  if (aStr != null){
		  for (int i=0;i<aStr.length;i++){
			  sBuffer.append("'").append(aStr[i]).append("'").append(",");
		  }
		  sBuffer.delete(sBuffer.length() - 1, sBuffer.length());
	  }else{
		  sBuffer = sBuffer.append("");
	  }
	  return sBuffer.toString();
  }

返回系统时间

int style 设置返回系统时间样式

string 返回系统时间样式

存在问题:中文乱码,但JSP中显示正常。

  static public String SysTime(String strStyle){
    String s = "";
    if (strStyle.compareTo("")==0){
    	strStyle = "yyyy-MM-dd HH:mm:ss";	
    }
    Date date=new Date();
    SimpleDateFormat dformat=new SimpleDateFormat(strStyle);
    s = dformat.format(date);
    return s;
  }

  static public String sysTime(){
    String s = "";
    Date date=new Date();
    SimpleDateFormat dformat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    s = dformat.format(date);
    return s;
  }

  static public String sysDate(){
    String s = "";
    Date date=new Date();
    SimpleDateFormat dformat=new SimpleDateFormat("yyyy-MM-dd");
    s = dformat.format(date);
    return s;
  }

是否为空

  public static boolean isNull(Object obj){
    try{
      if(obj==null){
    	  return true;
      }
      return false;
    }catch(Exception e){
      return false;
    }
  }
  
  public static boolean isNotNull(Object obj){
    try{
      if(obj==null){
    	  return false;
      }
      return true;
    }catch(Exception e){
      return true;
    }
  }  
  public static boolean isEmpty(String str){
    try{
      if(str==null || str.equals("null") || str.equals("")){
    	  return true;
      }
      return false;
    }catch(Exception e){
      return false;
    }
  }
  
  public static boolean isEmpty(String strs[]){
	  try{
		  if(strs==null || strs.length<=0){
			  return true;
		  }
		  return false;
	  }catch(Exception e){
		  return false;
	  }
  }

  public static boolean isNotEmpty(String str){
    try{
      if(str==null || str.equals("null") || str.equals("")){
    	  return false;
      }
      return true;
    }catch(Exception e){
      return true;
    }
  }

  public static boolean isNotEmpty(Object obj){
    try{
      if(obj==null || obj.toString().equals("null") || obj.toString().equals("")){
    	  return false;
      }
      return true;
    }catch(Exception e){
      return true;
    }
  }
  
  public static boolean isNotEmpty(List obj){
	  try{
		  if(obj==null || obj.size()<=0){
			  return false;
		  }
		  return true;
	  }catch(Exception e){
		  return true;
	  }
  }

用于转换为null的字段。

String strvalue 设置要转换的字符串

不为“null”的返回原串;为“null”返回""。

```java
  public static String convertNull(String strvalue)
  {
    try{
      if(strvalue.equals("null") || strvalue.length()==0){
        return "";
      }else{
        return strvalue.trim();
      }
    }catch(Exception e){
      return "";
    }
  }

  public static String[] convertNull(String[] aContent)
  {
    try{
      for(int i=0;i<aContent.length;i++){
        if(aContent[i].toLowerCase().compareTo("null")==0){
          aContent[i] = "";
        }
      }
      return aContent;
    }catch(Exception e){
      return null;
    }
  }
    
  public static String convertNull(Object o)
  {
    try{
      String strvalue = String.valueOf(o);
      if(strvalue.equals(null) || strvalue.equals("null") || strvalue.length()==0){
        return "";
      }else{
        return strvalue.trim();
      }
    }catch(Exception e){
      return "";
    }
  }

将为null的数据转为0,用在数值的值从数据库中读出的情况

  public static int ConvertZero(Object o)
  {
    try{
      String s = convertNull(o);
      if(s==""){
        return 0;
      }else{
        return Integer.parseInt(s);
      }
    }catch(Exception e){
      return 0;
    }
  }
`

``

将为null的数据转为0,用在数值的值从数据库中读出的情况

  public static int cvtPecrent(Object o)
  {
    try{
      String s = convertNull(o);
      if(s==""){
        return 0;
      }else{
        return Integer.parseInt(s);
      }
    }catch(Exception e){
      return 0;
    }
  }  
  
## if 0 then return "";
  public static String FormatZero(Object o)
  {
    try{
      String s = convertNull(o);
      if(s.compareTo("")==0){
        return "";
      }else{
        return String.valueOf(s);
      }
    }catch(Exception e){
      return "";
    }
  }

if 0 then return “”;

  public static String FormatZero(String s)
  {
    try{
      if(s.compareTo("0")==0){
        return "";
      }else{
        return s;
      }
    }catch(Exception e){
      return "";
    }

UrlEncoder 进行URL编码

public String UrlEncoder(String s)
{
String s1 = “”;
if(s == null)
return “”;
try
{
s1 = URLEncoder.encode(s);
}
catch(Exception e)
{
System.out.println(“URL Encoder :” + e.toString());
s1 = “”;
}
return s1;
}

URLDecoder 进行URL解码

   public String UrlDecoder(String s)
    {
        String s1 = "";
        if(s == null)
            return "";
        try
        {
            s1 = URLDecoder.decode(s);
        }
        catch(Exception e)
        {
            System.out.println("URL Encoder :" + e.toString());
            s1 = "";
        }
        return s1;
    }

将字符串转化成首字母大写,其余字母小写的格式

  public static String format_Aaa(String source) {

    if (source==null) return null;
    if (source.equals("")) return "";

    String a;
    a = source.substring(0, 1);
    a = a.toUpperCase();
    return a + source.substring(1);

  }

将字符串转换成Long型

  public static long parseLong(String param) {
    long l=0;
    try {
      l = Long.parseLong(param);
    }
    catch (Exception e) {
    }

    return l;
  }

将字符串转换成Float型

  public static float parseFloat(String param) {
    float l=0;
    try {
      l = Float.parseFloat(param);
    }
    catch (Exception e) {
    }

    return l;
  }

将字符串转换成Integer型

  public static int parseInt(String param) {
    int l=0;
    try {
      l = Integer.parseInt(param);
    }
    catch (Exception e) {
    }

    return l;
  }

将字符串转换成Double型

  public static double parseDouble(String param) {
    double l=0;
    try {
      l = Double.parseDouble(param);
    }
    catch (Exception e) {
    }

    return l;
  }

s是否存在ArrayList中,存在返回数组下标,不存在返回-1

  public static int existElements(String s,ArrayList aList) {
    try{
      for (int i = 0; i < aList.size(); i ++) {
        if (s.equals(aList.get(i))){
          return i;
        }
      }
    }catch(Exception e){   }
    return -1;
  }

s是否存在String数组中,存在返回数组下标,不存在返回-1

  public static int existElements(String s,String[] a) {
    try{
      for (int i = 0; i < a.length; i ++) {
        if (s.compareTo((a[i].trim()))==0){  
          return i;
        }
      }
    }catch(Exception e){   }
    return -1;
  }

判断对象o是否存在于set对象集合中

  public static boolean existElements(Object o, Set set) {
	  boolean isExists = false;
	  Iterator it = set.iterator();
	  while(it.hasNext())
	  {
	       Object obj = it.next();
	       if(o.equals(obj))
	       {
	    	   isExists=true;
	    	   break;
	       }
	  }
	  return isExists;
  }

s是否存在ArrayList中,存在返回数组下标,不存在返回-1

  public static int IsIndexOfElements(String s,ArrayList aList) {
    try{
      String s1 = "";
      for (int i = 0; i < aList.size(); i ++) {
        s1 = String.valueOf(aList.get(i));
        if (s1.indexOf(s)!=-1){
          return i;
        }
      }
    }catch(Exception e){   }
    return -1;
  }

将ArrayList转换为一维String数组,并把其中的null换成空字符串

  public String[] ArrayListToString(ArrayList aList) {
    String[] s = new String[aList.size()];
    for (int i = 0; i < aList.size(); i ++) {
      s[i] = this.convertNull(aList.get(i));
    }
    return s;
  }

将数组中的null换成空字符串

  public static void formatArrayList(ArrayList al) {

    for (int i = 0; i < al.size(); i ++) {
      if (al.get(i) == null)
        al.set(i, "");
    }

  }

StrToTimestamp 功能:将字符串转换为Timestamp 。

输入参数:String timestampStr 设置要转换的字符串 String pattern 要转换的format

输出参数:如果格式正确返回格式后的字符串。不正确返回系统日期。

  public static Timestamp StrToTimestamp(String timestampStr,String pattern) throws ParseException {
    Date date = null;
    SimpleDateFormat format = new SimpleDateFormat(pattern);
    try {
      date = format.parse(timestampStr);
    } catch (ParseException ex) {
      throw ex;
    }
    return date == null ? null : new Timestamp(date.getTime());
  }

  //ex:utilFuns.StrToDateTimeFormat("2005-12-01 00:00:00.0,"yyyy-MM-dd")
  public static String StrToDateTimeFormat(String timestampStr,String pattern) throws ParseException {
    String s ="";
    try{
      s = String.valueOf(StrToTimestamp(timestampStr, pattern));
      s = s.substring(0,pattern.length());
    }catch(Exception e){ }
    return s;
  }

  //ex:utilFuns.StrToDateTimeFormat("2005-12-01 00:00:00.0,"yyyy-MM-dd")
  public static String dateTimeFormat(Date date,String pattern) throws ParseException {
    String s ="";
    try{
        SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        s = dformat.format(date);
        s = String.valueOf(StrToTimestamp(s, pattern));
        s = s.substring(0,pattern.length());
    }catch(Exception e){ }
    return s;
  }
  public static String dateTimeFormat(Date date) throws ParseException {
	  String s ="";
	  try{
		  SimpleDateFormat dformat = new SimpleDateFormat("yyyy-MM-dd");
		  s = dformat.format(date);
		  s = String.valueOf(StrToTimestamp(s, "yyyy-MM-dd"));
		  s = s.substring(0,"yyyy-MM-dd".length());
	  }catch(Exception e){ }
	  return s;
  }
  
  //add by tony 20100228 转换中文 格式必须为:"yyyy-MM-dd HH:mm:ss"的一部分
  public static String formatDateTimeCN(String date) throws ParseException {
	  String s ="";
	  try{
		  if(UtilFuns.isEmpty(date)){
			  return "";
		  }
		  if(date.indexOf(".")>-1){
			  date = date.substring(0, date.indexOf("."));
		  }
		  if(date.length()==4){			//yyyy
			  s = date+"年";
		  }else if(date.length()==7){	//yyyy-MM
			  s = date.replaceAll("-0", "-").replaceFirst("-", "年")+"月";
		  }else if(date.length()==10){	//yyyy-MM-dd
			  s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月")+"日";
		  }else if(date.length()==2){	//HH
			  s = date+"时";
		  }else if(date.length()==5){	//HH:mm
			  s = date.replaceAll(":0", ":").replaceFirst(":", "时")+"分";
		  }else if(date.length()==8){	//HH:mm:ss
			  s = date.replaceAll(":0", ":").replaceFirst(":", "时").replaceFirst(":", "分")+"秒";
		  }else if(date.length()==13){	//yyyy-MM-dd HH
			  s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月").replaceAll(" 0", " ").replaceFirst(" ", "日")+"时";
		  }else if(date.length()==16){	//yyyy-MM-dd HH:mm
			  s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月").replaceAll(" 0", " ").replaceFirst(" ", "日").replaceAll(":0", ":").replaceFirst(":", "时")+"分";
		  }else if(date.length()==19){	//yyyy-MM-dd HH:mm:ss
			  s = date.replaceAll("-0", "-").replaceFirst("-", "年").replaceFirst("-", "月").replaceAll(" 0", " ").replaceFirst(" ", "日").replaceAll(":0", ":").replaceFirst(":", "时").replaceFirst(":", "分")+"秒";
		  }
		  s = s.replaceAll("0[时分秒]", "");	//正则 0时0分0秒的都替换为空
	  }catch(Exception e){ }
	  
	  return s;
  }
  
  //add by tony 2011-07-26 返回英文格式日期 oct.10.2011
  public static String formatDateEN(String date) throws ParseException {
	  String s ="";
	  int whichMonth = 1;
	  try{
		  if(UtilFuns.isEmpty(date)){
			  return "";
		  }
		  String[] aString = date.replaceAll("-0", "-").split("-");
		  whichMonth = Integer.parseInt(aString[1]);
		  if(whichMonth==1){
			  s = "Jan";
		  }else if(whichMonth==2){
			  s = "Feb";
		  }else if(whichMonth==3){
			  s = "Mar";
		  }else if(whichMonth==4){
			  s = "Apr";
		  }else if(whichMonth==5){
			  s = "May";
		  }else if(whichMonth==6){
			  s = "Jun";
		  }else if(whichMonth==7){
			  s = "Jul";
		  }else if(whichMonth==8){
			  s = "Aug";
		  }else if(whichMonth==9){
			  s = "Sept";
		  }else if(whichMonth==10){
			  s = "Oct";
		  }else if(whichMonth==11){
			  s = "Nov";
		  }else if(whichMonth==12){
			  s = "Dec";
		  }
		  s = s+"."+aString[2]+","+aString[0];
		  
	  }catch(Exception e){ }
	  
	  return s;
  }

  //返回年月格式 2010-7
  public String formatShortMonth(String strDate){
	  return strDate.substring(0,7).replaceAll("-0", "-");
  }
  
  //返回年月格式 2010-07
  public String formatMonth(String strDate){
	  return strDate.substring(0,7);
  }

删除最后1个字符

  public static String delLastChar(String s){
    try{
      if(s.length()>0){
        s = s.substring(0,s.length()-1);  
      }      
    }catch(Exception e){
      return "";
    }
    return s;
  }

删除最后len个字符

  public static String delLastChars(String s,int len){
    try{
      if(s.length()>0){
        s = s.substring(0,s.length()-len);  
      }      
    }catch(Exception e){
      return "";
    }
    return s;
  }
  

用于转换后几位的为*。

String strvalue 设置要转换的字符串

int Flag 位数。

 public static String getPassString( String strvalue, int Flag ) {
    try {
      if ( strvalue.equals("null") || strvalue.compareTo("")==0){
        return "";
      } else {
        int intStrvalue = strvalue.length();
        if ( intStrvalue > Flag ) {
          strvalue = strvalue.substring( 0, intStrvalue - Flag );

        }
        for ( int i = 0; i < Flag; i++ ) {
          strvalue = strvalue + "*";
        }

        //System.out.print( "strvalue:" + strvalue );
        return strvalue;
      }
    }
    catch (Exception e) {
      return strvalue;
    }
  }
  

getPassString 功能:用于转换为*。

String strvalue 设置要转换的字符串

int Flag 起位数。

int sFlag 末位数。

public static String getPassString( String strvalue, int Flag, int sFlag ,int iPassLen ) {
  try {
    
    if ( strvalue.equals( "null" ) ) {
      return "";
    } else {
      String strvalue1="";
      String strvalue2="";
      int intStrvalue = strvalue.length();
      if(sFlag>=Flag){
        if ( intStrvalue > Flag ) {
          strvalue1 = strvalue.substring( 0,  Flag );
          strvalue2 = strvalue.substring(  sFlag, intStrvalue );
        } else {
          strvalue1 = "";
          strvalue2 = "";
        }
        for ( int i = 0; i < iPassLen; i++ ) {
          strvalue1 = strvalue1 + "*";
        }
        strvalue=strvalue1+strvalue2;
      }
      //System.out.print( "strvalue:" + strvalue );
      return strvalue;
    }
  }
  catch (Exception e) {
    return strvalue;
  }
  } 

取得字符串iStartPos位置到iEndPos位置,将中间这部分转换iPatternLen个sPattern

EXSAMPLE:

	getPatternString("CHEN ZISHU",5,7,"*",3)
	RESULT: CHEN ***SHU

	getPatternString("CHEN ZISHU",10,0,".",3)
	RESULT: CHEN******
 */
  public static String getPatternString( String s, int iStartPos, int iEndPos, String sPattern, int iPatternLen ) {
    try {
	  if (iEndPos==0) {
		iEndPos = s.length();
	  }
	  
	  String sStartStr = "";
	  String sCenterStr = "";
	  String sEndStr = "";
	  
      if ( s.equals("null")){
        return "";
      } else {
        int ints = s.length();
        if ( ints > iStartPos ) {
          sStartStr = s.substring( 0, iStartPos );
        }else{
          return s;
        }
		if ( ints > iEndPos) {
          sEndStr = s.substring( iEndPos, ints );
		}
        for ( int i = 0; i < iPatternLen; i++ ) {
          sCenterStr = sCenterStr + sPattern;
        }
        return sStartStr + sCenterStr + sEndStr;
      }
    }
    catch (Exception e) {
      System.out.println(e);
      return s;
    }
  }

  public static String getPatternString( String s, int iStartPos, String sPattern, int iPatternLen ) {
    return getPatternString(s,iStartPos,0,sPattern,iPatternLen);
  }

  public static String getPatternString( String s, int iStartPos, String sPattern ) {
    return getPatternString(s,iStartPos,0,sPattern,3);
  }
相关标签: java