• Java_常用工具类收集


    一、日期工具类

    package com.ebd.application.common.utils;
    
    import java.sql.Timestamp;
    import java.text.DateFormat;
    import java.text.ParseException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    
    import org.apache.commons.lang.time.DateFormatUtils;
    
    /**
     * 日期工具类, 继承org.apache.commons.lang.time.DateUtils类
     */
    public class DateUtils extends org.apache.commons.lang.time.DateUtils {
    
    	private static String[] parsePatterns = { "yyyy-MM-dd",
    			"yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy/MM/dd",
    			"yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" };
    
    	/**
    	 * 得到当前日期字符串 格式(yyyy-MM-dd)
    	 */
    	public static String getDate() {
    		return getDate("yyyy-MM-dd");
    	}
    	
    	/**
    	 * Timestamp to Date String
    	 */
    	public static String timestamptoString(Long timestampStr) {
    		Timestamp ts = new Timestamp(timestampStr);   
            String dateStr = "";   
            DateFormat sdf = new SimpleDateFormat(parsePatterns[1]);   
            try {   
                dateStr = sdf.format(ts);   
            } catch (Exception e) {   
                e.printStackTrace();   
            }
            return dateStr;
    	}
    
    	/**
    	 * 得到当前日期字符串 格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
    	 */
    	public static String getDate(String pattern) {
    		return DateFormatUtils.format(new Date(), pattern);
    	}
    
    	/**
    	 * 得到日期字符串 默认格式(yyyy-MM-dd) pattern可以为:"yyyy-MM-dd" "HH:mm:ss" "E"
    	 */
    	public static String formatDate(Date date, Object... pattern) {
    		String formatDate = null;
    		if (pattern != null && pattern.length > 0) {
    			formatDate = DateFormatUtils.format(date, pattern[0].toString());
    		} else {
    			formatDate = DateFormatUtils.format(date, "yyyy-MM-dd");
    		}
    		return formatDate;
    	}
    
    	/**
    	 * 得到日期时间字符串,转换格式(yyyy-MM-dd HH:mm:ss)
    	 */
    	public static String formatDateTime(Date date) {
    		return formatDate(date, "yyyy-MM-dd HH:mm:ss");
    	}
    
    	/**
    	 * 得到当前时间字符串 格式(HH:mm:ss)
    	 */
    	public static String getTime() {
    		return formatDate(new Date(), "HH:mm:ss");
    	}
    
    	/**
    	 * 得到当前日期和时间字符串 格式(yyyy-MM-dd HH:mm:ss)
    	 */
    	public static String getDateTime() {
    		return formatDate(new Date(), "yyyy-MM-dd HH:mm:ss");
    	}
    
    	/**
    	 * 得到当前年份字符串 格式(yyyy)
    	 */
    	public static String getYear() {
    		return formatDate(new Date(), "yyyy");
    	}
    
    	/**
    	 * 得到当前月份字符串 格式(MM)
    	 */
    	public static String getMonth() {
    		return formatDate(new Date(), "MM");
    	}
    
    	/**
    	 * 得到当天字符串 格式(dd)
    	 */
    	public static String getDay() {
    		return formatDate(new Date(), "dd");
    	}
    
    	/**
    	 * 得到当前星期字符串 格式(E)星期几
    	 */
    	public static String getWeek() {
    		return formatDate(new Date(), "E");
    	}
    
    	/**
    	 * 日期型字符串转化为日期 格式 { "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm",
    	 * "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm" }
    	 */
    	public static Date parseDate(Object str) {
    		if (str == null) {
    			return null;
    		}
    		try {
    			return parseDate(str.toString(), parsePatterns);
    		} catch (ParseException e) {
    			return null;
    		}
    	}
    
    	/**
    	 * 获取过去的天数
    	 * 
    	 * @param date
    	 * @return
    	 */
    	public static long pastDays(Date date) {
    		long t = new Date().getTime() - date.getTime();
    		return t / (24 * 60 * 60 * 1000);
    	}
    
    	public static Date getDateStart(Date date) {
    		if (date == null) {
    			return null;
    		}
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		try {
    			date = sdf.parse(formatDate(date, "yyyy-MM-dd") + " 00:00:00");
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    		return date;
    	}
    
    	public static Date getDateEnd(Date date) {
    		if (date == null) {
    			return null;
    		}
    		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		try {
    			date = sdf.parse(formatDate(date, "yyyy-MM-dd") + " 23:59:59");
    		} catch (ParseException e) {
    			e.printStackTrace();
    		}
    		return date;
    	}
    
    }
    

    二、文件目录工具

    package com.ebd.application.common.utils;
    
    import java.io.File;
    import java.io.IOException;
    
    public class CreateFileUtil {
    
    	public static boolean createFile(String destFileName) {  
            File file = new File(destFileName);  
            if(file.exists()) {  
                System.out.println("创建单个文件" + destFileName + "失败,目标文件已存在!");  
                return false;  
            }  
            if (destFileName.endsWith(File.separator)) {  
                System.out.println("创建单个文件" + destFileName + "失败,目标文件不能为目录!");  
                return false;  
            }  
            //判断目标文件所在的目录是否存在  
            if(!file.getParentFile().exists()) {  
                //如果目标文件所在的目录不存在,则创建父目录  
                System.out.println("目标文件所在目录不存在,准备创建它!");  
                if(!file.getParentFile().mkdirs()) {  
                    System.out.println("创建目标文件所在目录失败!");  
                    return false;  
                }  
            }  
            //创建目标文件  
            try {  
                if (file.createNewFile()) {  
                    System.out.println("创建单个文件" + destFileName + "成功!");  
                    return true;  
                } else {  
                    System.out.println("创建单个文件" + destFileName + "失败!");  
                    return false;  
                }  
            } catch (IOException e) {  
                e.printStackTrace();  
                System.out.println("创建单个文件" + destFileName + "失败!" + e.getMessage());  
                return false;  
            }  
        }  
         
         
        public static boolean createDir(String destDirName) {  
            File dir = new File(destDirName);  
            if (dir.exists()) {  
                System.out.println(destDirName + "目录已经存在");  
                return true;  
            }  
            if (!destDirName.endsWith(File.separator)) {  
                destDirName = destDirName + File.separator;  
            }  
            //创建目录  
            if (dir.mkdirs()) {  
                System.out.println("创建目录" + destDirName + "成功!");  
                return true;  
            } else {  
                System.out.println("创建目录" + destDirName + "失败!");  
                return false;  
            }  
        }  
         
         
        public static String createTempFile(String prefix, String suffix, String dirName) {  
            File tempFile = null;  
            if (dirName == null) {  
                try{  
                    //在默认文件夹下创建临时文件  
                    tempFile = File.createTempFile(prefix, suffix);  
                    //返回临时文件的路径  
                    return tempFile.getCanonicalPath();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    System.out.println("创建临时文件失败!" + e.getMessage());  
                    return null;  
                }  
            } else {  
                File dir = new File(dirName);  
                //如果临时文件所在目录不存在,首先创建  
                if (!dir.exists()) {  
                    if (!CreateFileUtil.createDir(dirName)) {  
                        System.out.println("创建临时文件失败,不能创建临时文件所在的目录!");  
                        return null;  
                    }  
                }  
                try {  
                    //在指定目录下创建临时文件  
                    tempFile = File.createTempFile(prefix, suffix, dir);  
                    return tempFile.getCanonicalPath();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    System.out.println("创建临时文件失败!" + e.getMessage());  
                    return null;  
                }  
            }  
        }  
         
        public static void main(String[] args) {  
            //创建目录  
            String dirName = "D:/work/temp/temp0/temp1";  
            CreateFileUtil.createDir(dirName);  
            //创建文件  
            String fileName = dirName + "/temp2/tempFile.txt";  
            CreateFileUtil.createFile(fileName);  
            //创建临时文件  
            String prefix = "temp";  
            String suffix = ".txt";  
            for (int i = 0; i < 10; i++) {  
                System.out.println("创建了临时文件:"  
                        + CreateFileUtil.createTempFile(prefix, suffix, dirName));  
            }  
            //在默认目录下创建临时文件  
            for (int i = 0; i < 10; i++) {  
                System.out.println("在默认目录下创建了临时文件:"  
                        + CreateFileUtil.createTempFile(prefix, suffix, null));  
            }  
        }  
    }
    

    三、中文判断工具类 

    package com.ebd.application.common.utils;
    
    import java.util.regex.Pattern;
    
    /**
     * 中文判断工具类 
     * @author Administrator
     */
    public class CharUtil {
    	 
        public static void main(String[] args) {
            String[] strArr = new String[] { "www.micmiu.com", "!@#$%^&*()_+{}[]|"'?/:;<>,.", "!¥……()——:;“”‘’《》,。?、", "不要啊", "やめて", "韩佳人", "???" };
            for (String str : strArr) {
                System.out.println("===========> 测试字符串:" + str);
                System.out.println("正则判断结果:" + isChineseByREG(str) + " -- " + isChineseByName(str));
                System.out.println("Unicode判断结果 :" + isChinese(str));
                System.out.println("详细判断列表:");
                char[] ch = str.toCharArray();
                for (int i = 0; i < ch.length; i++) {
                    char c = ch[i];
                    System.out.println(c + " --> " + (isChinese(c) ? "是" : "否"));
                }
            }
        }
     
        // 根据Unicode编码完美的判断中文汉字和符号
        private static boolean isChinese(char c) {
            Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
            if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                    || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
                    || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
                    || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION) {
                return true;
            }
            return false;
        }
     
        // 完整的判断中文汉字和符号
        public static boolean isChinese(String strName) {
            char[] ch = strName.toCharArray();
            for (int i = 0; i < ch.length; i++) {
                char c = ch[i];
                if (isChinese(c)) {
                    return true;
                }
            }
            return false;
        }
     
        // 只能判断部分CJK字符(CJK统一汉字)
        public static boolean isChineseByREG(String str) {
            if (str == null) {
                return false;
            }
            Pattern pattern = Pattern.compile("[\u4E00-\u9FBF]+");
            return pattern.matcher(str.trim()).find();
        }
     
        // 只能判断部分CJK字符(CJK统一汉字)
        public static boolean isChineseByName(String str) {
            if (str == null) {
                return false;
            }
            // 大小写不同:\p 表示包含,\P 表示不包含
            // \p{Cn} 的意思为 Unicode 中未被定义字符的编码,\P{Cn} 就表示 Unicode中已经被定义字符的编码
            String reg = "\p{InCJK Unified Ideographs}&&\P{Cn}";
            Pattern pattern = Pattern.compile(reg);
            return pattern.matcher(str.trim()).find();
        }
    }
    

     四、文件上传工具

    package com.ebd.application.common.utils;
    
    import java.awt.geom.AffineTransform;
    import java.awt.image.AffineTransformOp;
    import java.awt.image.BufferedImage;
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.text.SimpleDateFormat;
    import java.util.Date;
    import java.util.Random;
    
    import javax.imageio.ImageIO;
    import javax.servlet.http.HttpServletRequest;
    
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.web.multipart.MultipartFile;
    
    public class FileUploadUtils {
    	
    	public static final String UPLOAD_URL  = "c:/pp";
    	
    	/**
    	 * 上传图片,图片的名称filename是根据时间+随机数组装成的
    	 * @param file MultipartFile file
    	 * @param request HttpServletRequest request,
    	 * @param uploadDir 上传的目的文件夹
    	 * @return 返回文件的上传地址 (uploadDir/filename)
    	 */
    	public static String upload(MultipartFile file, HttpServletRequest request,String uploadDir) {
    		String logoUrl = null;
    		if (file != null && !file.isEmpty()) {
    			System.out.println(request.getSession().getServletContext());
    			String filePath = request.getSession().getServletContext()
    					.getRealPath(uploadDir);
    			
    			//目录不存在时,新建目录
    			createDirectory(filePath);
    			
    			//得到原图片的后缀名
    			String srcfilename = file.getOriginalFilename();
    			String suffix=srcfilename.substring(srcfilename.lastIndexOf("."));
    			//组装新图片的名称
    			 SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMddHHmmssSSS");
    		     String format = dateFormat.format(new Date());
    		    
    			String filename = format+ new Random().nextInt(1000000)+suffix;
    			
    			File destFile = new File(filePath, filename);
    			//如果文件存在,继续随机名称
    			while(destFile.exists()){
    				filename = format+ new Random().nextInt(1000000)+suffix;
    				destFile = new File(filePath, filename);
    			}
    			
    			try {
    				file.transferTo(destFile);
    				logoUrl = uploadDir + "/" + filename;
    			} catch (IllegalStateException e) {
    				e.printStackTrace();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		return logoUrl;
    	}
    	
    	/**
    	 * 上传文件,文件名为源文件的名称
    	 * @param file
    	 * @param request
    	 * @param uploadDir
    	 * @return 上传文件的路径:uploadDir + "/" + srcfilename
    	 */
    	public static String uploadFile(MultipartFile file, HttpServletRequest request,String uploadDir) {
    		String logoUrl = null;
    		if (file != null && !file.isEmpty()) {
    			//获取上传文件夹的真实地址
    			String dirPath = request.getSession().getServletContext()
    					.getRealPath(uploadDir);
    			
    			//目录不存在时,新建目录
    			createDirectory(dirPath);
    			
    			//得到源文件的名称
    			String srcfilename = file.getOriginalFilename();
    			
    			//构建目标文件
    			File destFile = new File(dirPath, srcfilename);
    			try {
    				//上传文件
    				file.transferTo(destFile);
    				logoUrl = uploadDir + "/" + srcfilename;
    			} catch (IllegalStateException e) {
    				e.printStackTrace();
    			} catch (IOException e) {
    				e.printStackTrace();
    			}
    		}
    		return logoUrl;
    	}
    	
    	/**
    	 * 新建目录
    	 * @param dirPath
    	 */
    	public static void createDirectory(String dirPath){
    		if(StringUtils.isNotBlank(dirPath)){
    			// 获得文件对象  
    			File file = new File(dirPath);
    			if(!file.exists()){
    				// 如果路径不存在,则创建  
    				file.mkdirs();
    			}
    		}
    	}
    	
    	/** 
    	 * 删除单个文件 
    	 * @param   path    被删除文件的文件名 
    	 * @return 单个文件删除成功返回true,否则返回false 
    	 */  
    	public static boolean deleteFile(String path){
    		boolean flag = false;
    		File file = new File(path);
    		// 路径为文件且不为空则进行删除  
    		if(file.isFile() && file.exists()){
    			file.delete();
    			flag = true;
    		}
    		
    		return flag;
    	}
    	
    	/**
         * 生产缩略图
         * @param src 原图
         * @param dir 缩略图
         * @param fileName 缩略图名称
         * @return
         */
        public static String thumb(File src,File dir,String fileName,int nw,int nh){
        	
        	 try {  
                 /* 
                 AffineTransform 类表示 2D 仿射变换,它执行从 2D 坐标到其他 2D 
                                          坐标的线性映射,保留了线的“直线性”和“平行性”。可以使用一系 
                                          列平移、缩放、翻转、旋转和剪切来构造仿射变换。 
                 */  
                 AffineTransform transform = new AffineTransform();
                 //读取图片  
                 BufferedImage bis = ImageIO.read(src); 
                 int w = bis.getWidth();  
                 int h = bis.getHeight();  
                 double sx = (double)nw/w;  
                 double sy = (double)nh/h;  
                 //将此变换设置为缩放变换。  
                 transform.setToScale(sx,sy); 
                 /* 
                  * AffineTransformOp类使用仿射转换来执行从源图像或 Raster 中 2D 坐标到目标图像或 
                  * Raster 中 2D 坐标的线性映射。所使用的插值类型由构造方法通过 
                  * 一个 RenderingHints 对象或通过此类中定义的整数插值类型之一来指定。 
    			  * 如果在构造方法中指定了 RenderingHints 对象,则使用插值提示和呈现 
    			  * 的质量提示为此操作设置插值类型。要求进行颜色转换时,可以使用颜色 
    			  * 呈现提示和抖动提示。 注意,务必要满足以下约束:源图像与目标图像 
    			  * 必须不同。 对于 Raster 对象,源图像中的 band 数必须等于目标图像中 
    			  * 的 band 数。 
                 */  
                 AffineTransformOp ato = new AffineTransformOp(transform,null);  
                 BufferedImage bid = new BufferedImage(nw,nh,BufferedImage.TYPE_3BYTE_BGR);  
                 /* 
                  * TYPE_3BYTE_BGR 表示一个具有 8 位 RGB 颜色分量的图像, 
                  * 对应于 Windows 风格的 BGR 颜色模型,具有用 3 字节存 
                  * 储的 Blue、Green 和 Red 三种颜色。 
                 */  
                 ato.filter(bis,bid);  
                 ImageIO.write(bid,"jpeg",dir);  
             } catch(Exception e) {  
                 e.printStackTrace();  
             }  
        	
        	 return  dir + "/" + fileName;
        }
    	
    	
    	 /** 
         * 复制整个文件夹内容 
         * @param oldPath 
         * @param newPath 
         * @return boolean 
         */ 
       public static void copyFolder(String oldPath, String newPath) {
    
           try { 
        	   //如果文件夹不存在 则建立新文件夹 
               (new File(newPath)).mkdirs(); 
               File a=new File(oldPath); 
               String[] file=a.list(); 
               File temp=null; 
               for (int i = 0; i < file.length; i++) { 
                   if(oldPath.endsWith(File.separator)){ 
                       temp=new File(oldPath+file[i]); 
                   } 
                   else{ 
                       temp=new File(oldPath+File.separator+file[i]); 
                   }
    
                   if(temp.isFile()){ 
                       FileInputStream input = new FileInputStream(temp); 
                       FileOutputStream output = new FileOutputStream(newPath + "/" + 
                               (temp.getName()).toString()); 
                       byte[] b = new byte[1024 * 5]; 
                       int len; 
                       while ( (len = input.read(b)) != -1) { 
                           output.write(b, 0, len); 
                       } 
                       output.flush(); 
                       output.close(); 
                       input.close(); 
                   } 
                   if(temp.isDirectory()){//如果是子文件夹 
                       copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]); 
                   } 
               } 
           } 
           catch (Exception e) { 
               System.out.println("复制整个文件夹内容操作出错"); 
               e.printStackTrace();
    
           }
    
       }
       
       /** 
        * 删除文件夹 
        * @param filePathAndName
        * @param fileContent
        * @return boolean 
        */ 
      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) { 
              System.out.println("删除文件夹操作出错"); 
              e.printStackTrace();
    
          }
    
      }
    
      /** 
        * 删除文件夹里面的所有文件 
        * @param path
        */ 
      public static void delAllFile(String path) { 
          File file = new File(path); 
          if (!file.exists()) { 
              return; 
          } 
          if (!file.isDirectory()) { 
              return; 
          } 
          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]);//再删除空文件夹 
              } 
          } 
        }
      
    	  /** 
    	   * 移动文件到指定目录 
    	   * @param oldPath
    	   * @param newPath 
    	   */ 
    	public static void moveFile(String oldPath, String newPath) { 
    		copyFolder(oldPath, newPath); 
    		delFolder(oldPath);
    	
    	}
    	
    	public static void main(String[] args) {
    
    		//		System.out.println(new Date().getTime());
    //		System.out.println(String.valueOf(new Date().getTime()));
    ////		File f =new File("TileTest.doc");
    //	      String fileName="TileTest....6.6doc";
    //	      String prefix=fileName.substring(fileName.lastIndexOf("."));
    //	      System.out.println(prefix);
    //	      System.out.println(new Random().nextInt(1000000));
    //	      System.out.println(new Random().nextInt(1000000));
    //	      File f = new File("d:/1.txt");
    //	      System.out.println(f.exists());
    		
    		File src = new File("D:\dcd01448724c402a8cf8b852e1307510\qrcode_for_gh_cf64bce34a18_344.jpg");
    		File dir = new File("D:\dcd01448724c402a8cf8b852e1307510");
    //		File src = new File("D:\architecture\vungu\workspace0428\vp-standweb\src\main\webapp\fileUpload\images\subscribe\dcd01448724c402a8cf8b852e1307510\20160120171448178836077.png");
    //		File dir = new File("D:\architecture\vungu\workspace0428\vp-standweb\src\main\webapp\fileUpload\images\subscribe\dcd01448724c402a8cf8b852e1307510");
    		String fileName = "20160120171448178836077thumb.jpg";
    		int nw=360;
    		int nh=200;
    		thumb(src, dir, fileName, nw, nh);
    	}
    }
    

    五、UUID简单工具

    package com.ebd.application.common.utils;
    
    import java.security.SecureRandom;
    import java.util.UUID;
    
    public class Identities {
    	
    	private static SecureRandom random = new SecureRandom();
    	
    	public static String uuid() {
    	    return UUID.randomUUID().toString().replaceAll("-", "");
    	}
    
    	public static long randomLong() {
    		return Math.abs(random.nextLong());
    	}
    
    }
    

    六、JDBC工具

    package com.ebd.application.common.utils;
    
    import java.lang.reflect.Field;  
    import java.sql.Connection;  
    import java.sql.DriverManager;  
    import java.sql.PreparedStatement;  
    import java.sql.ResultSet;  
    import java.sql.ResultSetMetaData;  
    import java.sql.SQLException;  
    import java.util.ArrayList;  
    import java.util.HashMap;  
    import java.util.List;  
    import java.util.Map;  
    
    /**
     * JDBC工具类
     * @author Administrator
     */
    public class JdbcUtils {
    
        //数据库用户名  
        private static final String USERNAME = "root";  
        //数据库密码  
        private static final String PASSWORD = "root";  
        //驱动信息   
        private static final String DRIVER = "com.mysql.jdbc.Driver";  
        //数据库地址  
        private static final String URL = "jdbc:mysql://localhost:3306/test";  
        private Connection connection;  
        private PreparedStatement pstmt;  
        private ResultSet resultSet;  
        public JdbcUtils() {  
            // TODO Auto-generated constructor stub  
            try{  
                Class.forName(DRIVER);  
                System.out.println("数据库连接成功!");  
      
            }catch(Exception e){  
      
            }  
        }  
          
        /** 
         * 获得数据库的连接 
         * @return 
         */  
        public Connection getConnection(){  
            try {  
                connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);  
            } catch (SQLException e) {  
                // TODO Auto-generated catch block  
                e.printStackTrace();  
            }  
            return connection;  
        }  
      
          
        /** 
         * 增加、删除、改 
         * @param sql 
         * @param params 
         * @return 
         * @throws SQLException 
         */  
        public boolean updateByPreparedStatement(String sql, List<Object> params)throws SQLException{  
            boolean flag = false;  
            int result = -1;  
            pstmt = connection.prepareStatement(sql);  
            int index = 1;  
            if(params != null && !params.isEmpty()){  
                for(int i=0; i<params.size(); i++){  
                    pstmt.setObject(index++, params.get(i));  
                }  
            }  
            result = pstmt.executeUpdate();  
            flag = result > 0 ? true : false;  
            return flag;  
        }  
      
        /** 
         * 查询单条记录 
         * @param sql 
         * @param params 
         * @return 
         * @throws SQLException 
         */  
        public Map<String, Object> findSimpleResult(String sql, List<Object> params) throws SQLException{  
            Map<String, Object> map = new HashMap<String, Object>();  
            int index  = 1;  
            pstmt = connection.prepareStatement(sql);  
            if(params != null && !params.isEmpty()){  
                for(int i=0; i<params.size(); i++){  
                    pstmt.setObject(index++, params.get(i));  
                }  
            }  
            resultSet = pstmt.executeQuery();//返回查询结果  
            ResultSetMetaData metaData = resultSet.getMetaData();  
            int col_len = metaData.getColumnCount();  
            while(resultSet.next()){  
                for(int i=0; i<col_len; i++ ){  
                    String cols_name = metaData.getColumnName(i+1);  
                    Object cols_value = resultSet.getObject(cols_name);  
                    if(cols_value == null){  
                        cols_value = "";  
                    }  
                    map.put(cols_name, cols_value);  
                }  
            }  
            return map;  
        }  
      
        /**查询多条记录 
         * @param sql 
         * @param params 
         * @return 
         * @throws SQLException 
         */  
        public List<Map<String, Object>> findModeResult(String sql, List<Object> params) throws SQLException{  
            List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();  
            int index = 1;  
            pstmt = connection.prepareStatement(sql);  
            if(params != null && !params.isEmpty()){  
                for(int i = 0; i<params.size(); i++){  
                    pstmt.setObject(index++, params.get(i));  
                }  
            }  
            resultSet = pstmt.executeQuery();  
            ResultSetMetaData metaData = resultSet.getMetaData();  
            int cols_len = metaData.getColumnCount();  
            while(resultSet.next()){  
                Map<String, Object> map = new HashMap<String, Object>();  
                for(int i=0; i<cols_len; i++){  
                    String cols_name = metaData.getColumnName(i+1);  
                    Object cols_value = resultSet.getObject(cols_name);  
                    if(cols_value == null){  
                        cols_value = "";  
                    }  
                    map.put(cols_name, cols_value);  
                }  
                list.add(map);  
            }  
      
            return list;  
        }  
      
        /**通过反射机制查询单条记录 
         * @param sql 
         * @param params 
         * @param cls 
         * @return 
         * @throws Exception 
         */  
        public <T> T findSimpleRefResult(String sql, List<Object> params,  
                Class<T> cls )throws Exception{  
            T resultObject = null;  
            int index = 1;  
            pstmt = connection.prepareStatement(sql);  
            if(params != null && !params.isEmpty()){  
                for(int i = 0; i<params.size(); i++){  
                    pstmt.setObject(index++, params.get(i));  
                }  
            }  
            resultSet = pstmt.executeQuery();  
            ResultSetMetaData metaData  = resultSet.getMetaData();  
            int cols_len = metaData.getColumnCount();  
            while(resultSet.next()){  
                //通过反射机制创建一个实例  
                resultObject = cls.newInstance();  
                for(int i = 0; i<cols_len; i++){  
                    String cols_name = metaData.getColumnName(i+1);  
                    Object cols_value = resultSet.getObject(cols_name);  
                    if(cols_value == null){  
                        cols_value = "";  
                    }  
                    Field field = cls.getDeclaredField(cols_name);  
                    field.setAccessible(true); //打开javabean的访问权限  
                    field.set(resultObject, cols_value);  
                }  
            }  
            return resultObject;  
      
        }  
      
        /**通过反射机制查询多条记录 
         * @param sql  
         * @param params 
         * @param cls 
         * @return 
         * @throws Exception 
         */  
        public <T> List<T> findMoreRefResult(String sql, List<Object> params,  
                Class<T> cls )throws Exception {  
            List<T> list = new ArrayList<T>();  
            int index = 1;  
            pstmt = connection.prepareStatement(sql);  
            if(params != null && !params.isEmpty()){  
                for(int i = 0; i<params.size(); i++){  
                    pstmt.setObject(index++, params.get(i));  
                }  
            }  
            resultSet = pstmt.executeQuery();  
            ResultSetMetaData metaData  = resultSet.getMetaData();  
            int cols_len = metaData.getColumnCount();  
            while(resultSet.next()){  
                //通过反射机制创建一个实例  
                T resultObject = cls.newInstance();  
                for(int i = 0; i<cols_len; i++){  
                    String cols_name = metaData.getColumnName(i+1);  
                    Object cols_value = resultSet.getObject(cols_name);  
                    if(cols_value == null){  
                        cols_value = "";  
                    }  
                    Field field = cls.getDeclaredField(cols_name);  
                    field.setAccessible(true); //打开javabean的访问权限  
                    field.set(resultObject, cols_value);  
                }  
                list.add(resultObject);  
            }  
            return list;  
        }  
      
        /** 
         * 释放数据库连接 
         */  
        public void releaseConn(){  
            if(resultSet != null){  
                try{  
                    resultSet.close();  
                }catch(SQLException e){  
                    e.printStackTrace();  
                }  
            }  
        }  
      
        /** 
         * @param args 
         */  
        public static void main(String[] args) throws SQLException {  
            // TODO Auto-generated method stub  
            JdbcUtils jdbcUtils = new JdbcUtils();  
            jdbcUtils.getConnection();  
      
            /*******************增*********************/  
            /*      String sql = "insert into userinfo (username, pswd) values (?, ?), (?, ?), (?, ?)"; 
            List<Object> params = new ArrayList<Object>(); 
            params.add("小明"); 
            params.add("123xiaoming"); 
            params.add("张三"); 
            params.add("zhangsan"); 
            params.add("李四"); 
            params.add("lisi000"); 
            try { 
                boolean flag = jdbcUtils.updateByPreparedStatement(sql, params); 
                System.out.println(flag); 
            } catch (SQLException e) { 
                // TODO Auto-generated catch block 
                e.printStackTrace(); 
            }*/  
      
      
            /*******************删*********************/  
            //删除名字为张三的记录  
            /*      String sql = "delete from userinfo where username = ?"; 
            List<Object> params = new ArrayList<Object>(); 
            params.add("小明"); 
            boolean flag = jdbcUtils.updateByPreparedStatement(sql, params);*/  
      
            /*******************改*********************/  
            //将名字为李四的密码改了  
            /*      String sql = "update userinfo set pswd = ? where username = ? "; 
            List<Object> params = new ArrayList<Object>(); 
            params.add("lisi88888"); 
            params.add("李四"); 
            boolean flag = jdbcUtils.updateByPreparedStatement(sql, params); 
            System.out.println(flag);*/  
      
            /*******************查*********************/  
            //不利用反射查询多个记录  
            /*      String sql2 = "select * from userinfo "; 
            List<Map<String, Object>> list = jdbcUtils.findModeResult(sql2, null); 
            System.out.println(list);*/  
      
            //利用反射查询 单条记录  
    //        String sql = "select * from userinfo where username = ? ";  
    //        List<Object> params = new ArrayList<Object>();  
    //        params.add("李四");  
    //        UserInfo userInfo;  
    //        try {  
    //            userInfo = jdbcUtils.findSimpleRefResult(sql, params, UserInfo.class);  
    //            System.out.print(userInfo);  
    //        } catch (Exception e) {  
    //            // TODO Auto-generated catch block  
    //            e.printStackTrace();  
    //        }  
            
             String sql2 = "select * from student "; 
             List<Map<String, Object>> list = jdbcUtils.findModeResult(sql2, null); 
             System.out.println(list);
        }  
    }
    

    七、JsonUtil

    package com.ebd.application.common.utils;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.util.List;
    import java.util.Map;
    
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import org.apache.commons.lang3.BooleanUtils;
    
    import net.sf.json.JSONArray;
    import net.sf.json.JSONObject;
    import net.sf.json.JSONSerializer;
    
    public class JsonUtil extends BaseController{
    
    	@SuppressWarnings("unused")
    	private HttpServletRequest request;
    	private HttpServletResponse response ;
    	
    	public JsonUtil(HttpServletRequest request, HttpServletResponse response) {
    		this.request = request;
    		this.response = response;
    	}
    
    	/**
    	 * ajax后台封装jsonString
    	 * @param jsonStr
    	 * @throws IOException
    	 */
    	public void sendJson(String jsonStr) throws IOException {
    		
    		response.setContentType("text/html;charset=utf-8");
    		PrintWriter out = response.getWriter();
    		out.print(jsonStr);
    		out.flush();
    		out.close();
    	}
    	
    	/**
    	 * json字符串转成Java的Array数组
    	 * @param json
    	 * @param clazz
    	 * @return
    	 */
    	@SuppressWarnings("rawtypes")
    	public static Object[] readJSON2Array(String json, Class clazz) {
    		JSONArray jsonArray = JSONArray.fromObject(json);
    		Object[] infoList = (Object[]) JSONArray.toArray(jsonArray, clazz);
    		return infoList;
    	}
    	
    	/**
    	 * JSON字符串转成Java的List集合
    	 * @param json
    	 * @param clazz
    	 * @return
    	 */
    	@SuppressWarnings({ "rawtypes", "deprecation" })
    	public static List<?> readJSON2List(String json, Class clazz) {
    		JSONArray jsonArray = JSONArray.fromObject(json);
    		List<?> infoList = JSONArray.toList(jsonArray, clazz);
    		return infoList;
    	}
    	
    	/**
    	 * JSON对象反序列化成Java对象
    	 * @param json
    	 * @param clazz
    	 * @return
    	 */
    	@SuppressWarnings("rawtypes")
    	public static Object readJSON2Bean(String json, Class clazz) {
    		JSONObject jsonObject = JSONObject.fromObject(json);
    		Object bean = JSONObject.toBean(jsonObject, clazz);
    		return bean;
    	}
    	
    	/**
    	 * 生成json格式串
    	 * @param bean
    	 * @param isSeri
    	 * @param isFix
    	 * @return
    	 */
    	public static String writeBean2JSON(Object bean, boolean isSeri, boolean isFix) {
    		if (bean == null) {
    			return null;
    		}
    		String jsonStr = null;
    		if (BooleanUtils.isTrue(isSeri)) {
    			jsonStr = JSONSerializer.toJSON(bean).toString();
    			if (BooleanUtils.isTrue(isFix)) {
    				jsonStr = "[" + jsonStr + "]";
    			}
    		} else {
    			if (BooleanUtils.isTrue(isFix)) {
    				jsonStr = JSONArray.fromObject(bean).toString();
    			} else {
    				jsonStr = JSONObject.fromObject(bean).toString();
    			}
    		}
    		return jsonStr;
    	}
    	
    	/**
    	 * List生成Json
    	 * @param list
    	 * @param isSeri
    	 * @param isFix
    	 * @return
    	 */
    	public static String writeList2JSON(List<?> list, boolean isSeri,
    			boolean isFix) {
    		if (list == null) {
    			return null;
    		}
    		String jsonStr = null;
    		if (BooleanUtils.isTrue(isSeri)) {// 需要序列化
    			jsonStr = JSONSerializer.toJSON(list).toString();
    			if (BooleanUtils.isTrue(isFix)) {
    				jsonStr = "[" + jsonStr + "]";
    			}
    		} else {
    			if (BooleanUtils.isTrue(isFix)) {
    				jsonStr = JSONArray.fromObject(list).toString();
    			} else {
    				jsonStr = JSONObject.fromObject(list).toString();
    			}
    		}
    		return jsonStr;
    	}
    	
    	/**
    	 * Map生成Json
    	 * @param map
    	 * @param isSeri
    	 * @param isFix
    	 * @return
    	 */
    	public static String writeMap2JSON(Map<String, Object> map, boolean isSeri,
    			boolean isFix) {
    		String jsonStr = null;
    		if (BooleanUtils.isTrue(isSeri)) {// 序列化
    			jsonStr = JSONSerializer.toJSON(map).toString();
    			if (BooleanUtils.isTrue(isFix)) {
    				jsonStr = "[" + jsonStr + "]";
    			}
    		} else {
    			if (BooleanUtils.isTrue(isFix)) {
    				jsonStr = JSONArray.fromObject(map).toString();
    			} else {
    				jsonStr = JSONObject.fromObject(map).toString();
    			}
    		}
    		return jsonStr;
    	}
    	
    	/**
    	 * Json串转为Bean
    	 * @param json
    	 * @param clazz
    	 * @param subList
    	 * @return
    	 */
    	@SuppressWarnings("rawtypes")
    	public static Object readJSON2Bean(String json, Class clazz, Map<String, Object> subList) {
    		JSONObject jsonObject = JSONObject.fromObject(json);
    		Object bean = JSONObject.toBean(jsonObject, clazz, subList);
    		return bean;
    	}
    }
    

    八、SpringUtils

    package com.ebd.application.common.utils;
    
    import org.springframework.beans.BeansException;
    import org.springframework.beans.factory.NoSuchBeanDefinitionException;
    import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
    import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
    
    public final class SpringUtils implements BeanFactoryPostProcessor {
    
    	private static ConfigurableListableBeanFactory beanFactory; // Spring应用上下文环境
    
    	public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) throws BeansException {
    		SpringUtils.beanFactory = beanFactory;
    	}
    
    	/**
    	 * 获取对象
    	 * @param name
    	 * @return Object 一个以所给名字注册的bean的实例
    	 * @throws org.springframework.beans.BeansException
    	 */
    	@SuppressWarnings("unchecked")
    	public static <T> T getBean(String name) throws BeansException {
    		return (T) beanFactory.getBean(name);
    	}
    
    	/**
    	 * 获取类型为requiredType的对象
    	 * @param clz
    	 * @return
    	 * @throws org.springframework.beans.BeansException
    	 * 
    	 */
    	public static <T> T getBean(Class<T> clz) throws BeansException {
    		T result = (T) beanFactory.getBean(clz);
    		return result;
    	}
    
    	/**
    	 * 如果BeanFactory包含一个与所给名称匹配的bean定义,则返回true
    	 * 
    	 * @param name
    	 * @return boolean
    	 */
    	public static boolean containsBean(String name) {
    		return beanFactory.containsBean(name);
    	}
    
    	/**
    	 * 判断以给定名字注册的bean定义是一个singleton还是一个prototype。
    	 * 如果与给定名字相应的bean定义没有被找到,将会抛出一个异常(NoSuchBeanDefinitionException)
    	 * 
    	 * @param name
    	 * @return boolean
    	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
    	 * 
    	 */
    	public static boolean isSingleton(String name) throws NoSuchBeanDefinitionException {
    		return beanFactory.isSingleton(name);
    	}
    
    	/**
    	 * @param name
    	 * @return Class 注册对象的类型
    	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
    	 * 
    	 */
    	public static Class<?> getType(String name) throws NoSuchBeanDefinitionException {
    		return beanFactory.getType(name);
    	}
    
    	/**
    	 * 如果给定的bean名字在bean定义中有别名,则返回这些别名
    	 * 
    	 * @param name
    	 * @return
    	 * @throws org.springframework.beans.factory.NoSuchBeanDefinitionException
    	 * 
    	 */
    	public static String[] getAliases(String name) throws NoSuchBeanDefinitionException {
    		return beanFactory.getAliases(name);
    	}
    
    }
    

      

  • 相关阅读:
    Socket 的网络编程
    《Python 3.5从零开始学》笔记-第8章 面向对象编程
    Python 的8个关键要素
    分布式发布订阅模型网络的实现有哪些
    MongoDB知识整理
    C++模板类与Qt信号槽混用
    C++中 =default,=delete用法
    QT知识整理
    Python题整理
    STL库的应用
  • 原文地址:https://www.cnblogs.com/eRrsr/p/8368236.html
Copyright © 2020-2023  润新知