java常用工具类(二)

1、FtpUtil

  1. package com.itjh.javaUtil;  
  2.   
  3. import java.io.File;  
  4. import java.io.FileOutputStream;  
  5. import java.io.IOException;  
  6. import java.io.OutputStream;  
  7. import java.util.ArrayList;  
  8. import java.util.List;  
  9.   
  10. import org.apache.commons.net.ftp.FTPClient;  
  11. import org.apache.commons.net.ftp.FTPFile;  
  12. import org.apache.commons.net.ftp.FTPReply;  
  13.   
  14. /** 
  15.  * 用来操作ftp的综合类。<br/> 
  16.  * 主要依赖jar包commons-net-3.1.jar。 
  17.  *  
  18.  * @author 宋立君 
  19.  * @date 2014年06月25日 
  20.  */  
  21. public class FtpUtil {  
  22.     // ftp 地址  
  23.     private String url;  
  24.     // ftp端口  
  25.     private int port;  
  26.     // 用户名  
  27.     private String userName;  
  28.     // 密码  
  29.     private String password;  
  30.   
  31.     /** 
  32.      * 构造函数 
  33.      *  
  34.      * @param url 
  35.      *            ftp地址 
  36.      * @param port 
  37.      *            ftp端口 
  38.      * @param userName 
  39.      *            用户名 
  40.      * @param password 
  41.      *            密码 
  42.      * @author 宋立君 
  43.      * @date 2014年06月25日 
  44.      * 
  45.      */  
  46.     public FtpUtil(String url, int port, String userName, String password) {  
  47.         this.url = url;  
  48.         this.port = port;  
  49.         this.userName = userName;  
  50.         this.password = password;  
  51.     }  
  52.   
  53.     /** 
  54.      * 从FTP服务器下载指定文件名的文件。 
  55.      *  
  56.      * @param remotePath 
  57.      *            FTP服务器上的相对路径 
  58.      * @param fileName 
  59.      *            要下载的文件名 
  60.      * @param localPath 
  61.      *            下载后保存到本地的路径 
  62.      * @return 成功下载返回true,否则返回false。 
  63.      * @throws IOException 
  64.      * @author 宋立君 
  65.      * @date 2014年06月25日 
  66.      */  
  67.     public boolean downFile(String remotePath, String fileName, String localPath)  
  68.             throws IOException {  
  69.         boolean success = false;  
  70.         FTPClient ftp = new FTPClient();  
  71.         try {  
  72.             int reply;  
  73.             ftp.connect(url, port);  
  74.             // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
  75.             ftp.login(userName, password);// 登录  
  76.             reply = ftp.getReplyCode();  
  77.             if (!FTPReply.isPositiveCompletion(reply)) {  
  78.                 ftp.disconnect();  
  79.                 return success;  
  80.             }  
  81.             ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  
  82.             FTPFile[] fs = ftp.listFiles();  
  83.             FTPFile ff;  
  84.             for (int i = 0; i < fs.length; i++) {  
  85.                 ff = fs[i];  
  86.                 if (null != ff && null != ff.getName()  
  87.                         && ff.getName().equals(fileName)) {  
  88.                     File localFile = new File(localPath + "/" + ff.getName());  
  89.                     OutputStream is = new FileOutputStream(localFile);  
  90.                     ftp.retrieveFile(ff.getName(), is);  
  91.                     is.close();  
  92.                 }  
  93.             }  
  94.             ftp.logout();  
  95.             success = true;  
  96.         } catch (IOException e) {  
  97.             e.printStackTrace();  
  98.             throw e;  
  99.         } finally {  
  100.             if (ftp.isConnected()) {  
  101.                 try {  
  102.                     ftp.disconnect();  
  103.                 } catch (IOException ioe) {  
  104.                 }  
  105.             }  
  106.         }  
  107.         return success;  
  108.     }  
  109.   
  110.     /** 
  111.      * 从FTP服务器列出指定文件夹下文件名列表。 
  112.      *  
  113.      * @param remotePath 
  114.      *            FTP服务器上的相对路径 
  115.      * @return List<String> 文件名列表,如果出现异常返回null。 
  116.      * @throws IOException 
  117.      * @author 宋立君 
  118.      * @date 2014年06月25日 
  119.      */  
  120.     public List<String> getFileNameList(String remotePath) throws IOException {  
  121.         // 目录列表记录  
  122.         List<String> fileNames = new ArrayList<String>();  
  123.         FTPClient ftp = new FTPClient();  
  124.         try {  
  125.             int reply;  
  126.             ftp.connect(url, port);  
  127.             // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
  128.             ftp.login(userName, password);// 登录  
  129.             reply = ftp.getReplyCode();  
  130.             if (!FTPReply.isPositiveCompletion(reply)) {  
  131.                 ftp.disconnect();  
  132.                 return null;  
  133.             }  
  134.             ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  
  135.             FTPFile[] fs = ftp.listFiles();  
  136.             for (FTPFile file : fs) {  
  137.                 fileNames.add(file.getName());  
  138.             }  
  139.             ftp.logout();  
  140.         } catch (IOException e) {  
  141.             e.printStackTrace();  
  142.             throw e;  
  143.         } finally {  
  144.             if (ftp.isConnected()) {  
  145.                 try {  
  146.                     ftp.disconnect();  
  147.                 } catch (IOException ioe) {  
  148.                 }  
  149.             }  
  150.         }  
  151.         return fileNames;  
  152.     }  
  153.   
  154. }  

2、 汉字转拼音

  1. package com.itjh.test;  
  2.   
  3. import net.sourceforge.pinyin4j.PinyinHelper;  
  4. import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;  
  5. import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;  
  6. import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;  
  7. import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;  
  8.   
  9.   
  10. public class SpellHelper {  
  11.      //将中文转换为英文  
  12.      public static String getEname(String name) {  
  13.            HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat();  
  14.            pyFormat.setCaseType(HanyuPinyinCaseType. LOWERCASE);  
  15.           pyFormat.setToneType(HanyuPinyinToneType. WITHOUT_TONE);  
  16.            pyFormat.setVCharType(HanyuPinyinVCharType. WITH_V);  
  17.   
  18.             return PinyinHelper. toHanyuPinyinString(name, pyFormat, "");  
  19.      }  
  20.   
  21.      //姓、名的第一个字母需要为大写  
  22.      public static String getUpEname(String name) {  
  23.             char[] strs = name.toCharArray();  
  24.            String newname = null;  
  25.                  
  26.         //名字的长度  
  27.      if (strs.length == 2) {     
  28.                 newname = toUpCase(getEname ("" + strs[0])) + " "  
  29.                            + toUpCase(getEname ("" + strs[1]));  
  30.            } else if (strs. length == 3) {  
  31.                 newname = toUpCase(getEname ("" + strs[0])) + " "  
  32.                            + toUpCase(getEname ("" + strs[1] + strs[2]));  
  33.            } else if (strs. length == 4) {  
  34.                 newname = toUpCase(getEname ("" + strs[0] + strs[1])) + " "  
  35.                            + toUpCase(getEname ("" + strs[2] + strs[3]));  
  36.            } else {  
  37.                 newname = toUpCase(getEname (name));  
  38.            }  
  39.   
  40.             return newname;  
  41.      }  
  42.   
  43.      //首字母大写  
  44.      private static String toUpCase(String str) {  
  45.            StringBuffer newstr = new StringBuffer();  
  46.            newstr.append((str.substring(01)).toUpperCase()).append(  
  47.                      str.substring(1, str.length()));  
  48.   
  49.             return newstr.toString();  
  50.      }  
  51.   
  52.      public static void main(String[] args) {  
  53.            System. out.println( getEname("李宇春"));  
  54.   
  55.      }  
  56.   
  57. }  

3、zip工具类

  1. package com.itjh.javaUtil;  
  2.   
  3. import java.io.BufferedInputStream;  
  4. import java.io.BufferedOutputStream;  
  5. import java.io.File;  
  6. import java.io.FileInputStream;  
  7. import java.io.FileOutputStream;  
  8. import java.io.IOException;  
  9. import java.io.InputStream;  
  10. import java.io.OutputStream;  
  11. import java.util.Enumeration;  
  12.   
  13. import org.apache.commons.compress.archivers.zip.Zip64Mode;  
  14. import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;  
  15. import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;  
  16. import org.apache.commons.compress.archivers.zip.ZipFile;  
  17. import org.apache.commons.compress.utils.IOUtils;  
  18.   
  19. /** 
  20.  * Zip工具栏类,依赖于commons-compress-1.5.jar。 
  21.  *  
  22.  * @author 宋立君 
  23.  * @date 2014年06月25日 
  24.  */  
  25. public class ZipUtil {  
  26.   
  27.     // public static void main(String[] args){  
  28.     // try {  
  29.     // //new ZipUtil().decompressZip(new  
  30.     // File("d://img.zip"),"img/pic20140626.jpg","d://");  
  31.     // new ZipUtil().decompressZip(new File("d://img.zip"),"flight.log","d://");  
  32.     // //new File("d://flight.log").delete();  
  33.     // //ZipUtil.compress(new File("D://测试压缩文件"),new File("d://img.zip"));  
  34.     // // ZipUtil.compress(new File[]{new  
  35.     // File("F:/testZIP/testzip.txt"),new File("d://ftp"),new  
  36.     // File("e://ftp")},new File("d://压缩文件.zip"));  
  37.     // } catch (IOException e) {  
  38.     // e.printStackTrace();  
  39.     // }  
  40.     // }  
  41.   
  42.     /** 
  43.      * 把N多文件或文件夹压缩成zip。 
  44.      *  
  45.      * @param files 
  46.      *            需要压缩的文件或文件夹。 
  47.      * @param zipFilePath 
  48.      *            压缩后的zip文件 
  49.      * @throws IOException 
  50.      *             压缩时IO异常。 
  51.      * @author 宋立君 
  52.      * @date 2014年06月25日 
  53.      */  
  54.     public static void compress(File[] files, File zipFile) throws IOException {  
  55.         if (CollectionUtil.isEmpty(files)) {  
  56.             return;  
  57.         }  
  58.         ZipArchiveOutputStream out = new ZipArchiveOutputStream(zipFile);  
  59.         out.setUseZip64(Zip64Mode.AsNeeded);  
  60.         // 将每个文件用ZipArchiveEntry封装  
  61.         for (File file : files) {  
  62.             if (file == null) {  
  63.                 continue;  
  64.             }  
  65.             compressOneFile(file, out, "");  
  66.         }  
  67.         if (out != null) {  
  68.             out.close();  
  69.         }  
  70.     }  
  71.   
  72.     /** 
  73.      * 功能:压缩文件或文件夹。 
  74.      *  
  75.      * @author 宋立君 
  76.      * @date 2014年06月25日 
  77.      * @param srcFile 
  78.      *            源文件。 
  79.      * @param destFile 
  80.      *            压缩后的文件 
  81.      * @throws IOException 
  82.      *             压缩时出现了异常。 
  83.      */  
  84.     public static void compress(File srcFile, File destFile) throws IOException {  
  85.         ZipArchiveOutputStream out = null;  
  86.         try {  
  87.             out = new ZipArchiveOutputStream(new BufferedOutputStream(  
  88.                     new FileOutputStream(destFile), 1024));  
  89.             compressOneFile(srcFile, out, "");  
  90.         } finally {  
  91.             out.close();  
  92.         }  
  93.     }  
  94.   
  95.     /** 
  96.      * 功能:压缩单个文件,非文件夹。私有,不对外开放。 
  97.      *  
  98.      * @author 宋立君 
  99.      * @date 2014年06月25日 
  100.      * @param srcFile 
  101.      *            源文件,不能是文件夹。 
  102.      * @param out 
  103.      *            压缩文件的输出流。 
  104.      * @param destFile 
  105.      *            压缩后的文件 
  106.      * @param dir 
  107.      *            在压缩包中的位置,根目录传入/。 
  108.      * @throws IOException 
  109.      *             压缩时出现了异常。 
  110.      */  
  111.     private static void compressOneFile(File srcFile,  
  112.             ZipArchiveOutputStream out, String dir) throws IOException {  
  113.         if (srcFile.isDirectory()) {// 对文件夹进行处理。  
  114.             ZipArchiveEntry entry = new ZipArchiveEntry(dir + srcFile.getName()  
  115.                     + "/");  
  116.             out.putArchiveEntry(entry);  
  117.             out.closeArchiveEntry();  
  118.             // 循环文件夹中的所有文件进行压缩处理。  
  119.             String[] subFiles = srcFile.list();  
  120.             for (String subFile : subFiles) {  
  121.                 compressOneFile(new File(srcFile.getPath() + "/" + subFile),  
  122.                         out, (dir + srcFile.getName() + "/"));  
  123.             }  
  124.         } else { // 普通文件。  
  125.             InputStream is = null;  
  126.             try {  
  127.                 is = new BufferedInputStream(new FileInputStream(srcFile));  
  128.                 // 创建一个压缩包。  
  129.                 ZipArchiveEntry entry = new ZipArchiveEntry(srcFile, dir  
  130.                         + srcFile.getName());  
  131.                 out.putArchiveEntry(entry);  
  132.                 IOUtils.copy(is, out);  
  133.                 out.closeArchiveEntry();  
  134.             } finally {  
  135.                 if (is != null)  
  136.                     is.close();  
  137.             }  
  138.         }  
  139.     }  
  140.   
  141.     /** 
  142.      * 功能:解压缩zip压缩包下的所有文件。 
  143.      *  
  144.      * @author 宋立君 
  145.      * @date 2014年06月25日 
  146.      * @param zipFile 
  147.      *            zip压缩文件 
  148.      * @param dir 
  149.      *            解压缩到这个路径下 
  150.      * @throws IOException 
  151.      *             文件流异常 
  152.      */  
  153.     public void decompressZip(File zipFile, String dir) throws IOException {  
  154.         ZipFile zf = new ZipFile(zipFile);  
  155.         try {  
  156.             for (Enumeration<ZipArchiveEntry> entries = zf.getEntries(); entries  
  157.                     .hasMoreElements();) {  
  158.                 ZipArchiveEntry ze = entries.nextElement();  
  159.                 // 不存在则创建目标文件夹。  
  160.                 File targetFile = new File(dir, ze.getName());  
  161.                 // 遇到根目录时跳过。  
  162.                 if (ze.getName().lastIndexOf("/") == (ze.getName().length() - 1)) {  
  163.                     continue;  
  164.                 }  
  165.                 // 如果文件夹不存在,创建文件夹。  
  166.                 if (!targetFile.getParentFile().exists()) {  
  167.                     targetFile.getParentFile().mkdirs();  
  168.                 }  
  169.   
  170.                 InputStream i = zf.getInputStream(ze);  
  171.                 OutputStream o = null;  
  172.                 try {  
  173.                     o = new FileOutputStream(targetFile);  
  174.                     IOUtils.copy(i, o);  
  175.                 } finally {  
  176.                     if (i != null) {  
  177.                         i.close();  
  178.                     }  
  179.                     if (o != null) {  
  180.                         o.close();  
  181.                     }  
  182.                 }  
  183.             }  
  184.         } finally {  
  185.             zf.close();  
  186.         }  
  187.     }  
  188.   
  189.     /** 
  190.      * 功能:解压缩zip压缩包下的某个文件信息。 
  191.      *  
  192.      * @author 宋立君 
  193.      * @date 2014年06月25日 
  194.      * @param zipFile 
  195.      *            zip压缩文件 
  196.      * @param fileName 
  197.      *            某个文件名,例如abc.zip下面的a.jpg,需要传入/abc/a.jpg。 
  198.      * @param dir 
  199.      *            解压缩到这个路径下 
  200.      * @throws IOException 
  201.      *             文件流异常 
  202.      */  
  203.     public void decompressZip(File zipFile, String fileName, String dir)  
  204.             throws IOException {  
  205.         // 不存在则创建目标文件夹。  
  206.         File targetFile = new File(dir, fileName);  
  207.         if (!targetFile.getParentFile().exists()) {  
  208.             targetFile.getParentFile().mkdirs();  
  209.         }  
  210.   
  211.         ZipFile zf = new ZipFile(zipFile);  
  212.         Enumeration<ZipArchiveEntry> zips = zf.getEntries();  
  213.         ZipArchiveEntry zip = null;  
  214.         while (zips.hasMoreElements()) {  
  215.             zip = zips.nextElement();  
  216.             if (fileName.equals(zip.getName())) {  
  217.                 OutputStream o = null;  
  218.                 InputStream i = zf.getInputStream(zip);  
  219.                 try {  
  220.                     o = new FileOutputStream(targetFile);  
  221.                     IOUtils.copy(i, o);  
  222.                 } finally {  
  223.                     if (i != null) {  
  224.                         i.close();  
  225.                     }  
  226.                     if (o != null) {  
  227.                         o.close();  
  228.                     }  
  229.                 }  
  230.             }  
  231.         }  
  232.     }  
  233.   
  234.     /** 
  235.      * 功能:得到zip压缩包下的某个文件信息,只能在根目录下查找。 
  236.      *  
  237.      * @author 宋立君 
  238.      * @date 2014年06月25日 
  239.      * @param zipFile 
  240.      *            zip压缩文件 
  241.      * @param fileName 
  242.      *            某个文件名,例如abc.zip下面的a.jpg,需要传入/abc/a.jpg。 
  243.      * @return ZipArchiveEntry 压缩文件中的这个文件,没有找到返回null。 
  244.      * @throws IOException 
  245.      *             文件流异常 
  246.      */  
  247.     public ZipArchiveEntry readZip(File zipFile, String fileName)  
  248.             throws IOException {  
  249.         ZipFile zf = new ZipFile(zipFile);  
  250.         Enumeration<ZipArchiveEntry> zips = zf.getEntries();  
  251.         ZipArchiveEntry zip = null;  
  252.         while (zips.hasMoreElements()) {  
  253.             zip = zips.nextElement();  
  254.             if (fileName.equals(zip.getName())) {  
  255.                 return zip;  
  256.             }  
  257.         }  
  258.         return null;  
  259.     }  
  260.   
  261.     /** 
  262.      * 功能:得到zip压缩包下的所有文件信息。 
  263.      *  
  264.      * @author 宋立君 
  265.      * @date 2014年06月25日 
  266.      * @param zipFile 
  267.      *            zip压缩文件 
  268.      * @return Enumeration<ZipArchiveEntry> 压缩文件中的文件枚举。 
  269.      * @throws IOException 
  270.      *             文件流异常 
  271.      */  
  272.     public Enumeration<ZipArchiveEntry> readZip(File zipFile)  
  273.             throws IOException {  
  274.         ZipFile zf = new ZipFile(zipFile);  
  275.         Enumeration<ZipArchiveEntry> zips = zf.getEntries();  
  276.         return zips;  
  277.     }  
  278. }  

4 CollectionUtil代码:

  1. package com.itjh.javaUtil;  
  2.   
  3. import java.util.Collection;  
  4. import java.util.LinkedList;  
  5. import java.util.List;  
  6. import java.util.Map;  
  7.   
  8. /**  
  9.  * 集合(List,Map,Set)辅助类。  
  10.  * @author 宋立君  
  11.  * @date 2014年06月25日  
  12.  */  
  13. public class CollectionUtil {  
  14.       
  15.     /**  
  16.      * 功能:从List中随机取出一个元素。  
  17.      * @author 宋立君  
  18.      * @date 2014年06月25日  
  19.      * @param objs 源List  
  20.      * @return T List的一个元素  
  21.      */  
  22.     public static <T> T randomOne(List<T> list){  
  23.         if(isEmpty(list)){  
  24.             return null;  
  25.         }  
  26.         return list.get(MathUtil.randomNumber(0, list.size()));  
  27.     }  
  28.       
  29.     /**  
  30.      * 功能:从数组中随机取出一个元素。  
  31.      * @author 宋立君  
  32.      * @date 2014年06月25日  
  33.      * @param objs 源数组  
  34.      * @return T 数组的一个元素  
  35.      */  
  36.     public static <T> T randomOne(T[] objs){  
  37.         if(isEmpty(objs)){  
  38.             return null;  
  39.         }  
  40.         return objs[MathUtil.randomNumber(0, objs.length)];  
  41.     }  
  42.       
  43.     /**  
  44.      * 功能:数组中是否存在这个元素。  
  45.      * @author 宋立君  
  46.      * @date 2014年06月25日  
  47.      * @param objArr 数组  
  48.      * @param compare 元素  
  49.      * @return 存在返回true,否则返回false。  
  50.      */  
  51.     public static <T> boolean arrayContain(T[] objArr,T compare){  
  52.         if(isEmpty(objArr)){  
  53.             return false;  
  54.         }  
  55.         for(T obj : objArr){  
  56.             if(obj.equals(compare)){  
  57.                 return true;  
  58.             }  
  59.         }  
  60.         return false;  
  61.     }  
  62.       
  63.   
  64.     /**  
  65.      * 功能:向list中添加数组。  
  66.      * @author 宋立君  
  67.      * @date 2014年06月25日  
  68.      * @param list List  
  69.      * @param array 数组  
  70.      */  
  71.     public static <T> void addArrayToList(List<T> list, T[] array) {  
  72.         if (isEmpty(list)) {  
  73.             return;  
  74.         }  
  75.         for (T t : array) {  
  76.             list.add(t);  
  77.         }  
  78.     }  
  79.       
  80.     /**  
  81.      * 功能:将数组进行反转,倒置。  
  82.      * @author 宋立君  
  83.      * @date 2014年06月25日  
  84.      * @param objs 源数组  
  85.      * @return T[] 反转后的数组  
  86.      */  
  87.     public static <T> T[] reverseArray(T[] objs){  
  88.         if(isEmpty(objs)){  
  89.             return null;  
  90.         }  
  91.         T[] res=(T[])java.lang.reflect.Array.newInstance(objs[0].getClass(), objs.length);  
  92.         //新序号  
  93.         int k=0;  
  94.         for(int i=objs.length-1 ; i>=0 ; i--){  
  95.             res[k++]=objs[i];  
  96.         }  
  97.         return res;  
  98.     }  
  99.       
  100.     /**  
  101.      * 功能:将数组转为list。  
  102.      * @author 宋立君  
  103.      * @date 2014年06月25日  
  104.      * @param objs 源数组  
  105.      * @return List  
  106.      */  
  107.     public static <T> List<T> arrayToList(T[] objs){  
  108.         if(isEmpty(objs)){  
  109.             return null;  
  110.         }  
  111.         List<T> list=new LinkedList<T>();  
  112.         for(T obj : objs){  
  113.             list.add(obj);  
  114.         }  
  115.         return list;  
  116.     }  
  117.       
  118.     /**  
  119.      * 功能:将list转为数组。  
  120.       * @author 宋立君  
  121.      * @date 2014年06月25日  
  122.      * @param list 源list  
  123.      * @return T[]  
  124.      */  
  125.     public static <T> T[] listToArray(List<T> list){  
  126.         if(isEmpty(list)){  
  127.             return null;  
  128.         }  
  129.         T[] objs=(T[])java.lang.reflect.Array.newInstance(list.get(0).getClass(), list.size());  
  130.         int i=0; //数组下标。  
  131.         for(T obj : list){  
  132.             objs[i++]=obj;  
  133.         }  
  134.         return objs;  
  135.     }  
  136.       
  137.     /**  
  138.      * 将一个字符串数组的内容全部添加到另外一个数组中,并返回一个新数组。  
  139.      * @param array1 第一个数组  
  140.      * @param array2 第二个数组  
  141.      * @return T[] 拼接后的新数组  
  142.      */  
  143.     public static <T> T[] concatenateArrays(T[] array1, T[] array2) {  
  144.         if (isEmpty(array1)) {  
  145.             return array2;  
  146.         }  
  147.         if (isEmpty(array2)) {  
  148.             return array1;  
  149.         }  
  150.         T[] resArray=(T[])java.lang.reflect.Array.newInstance(array1[0].getClass(), array1.length+array2.length);  
  151.         System.arraycopy(array1, 0, resArray, 0, array1.length);  
  152.         System.arraycopy(array2, 0, resArray, array1.length, array2.length);  
  153.         return resArray;  
  154.     }  
  155.       
  156.     /**  
  157.      * 将一个object添加到一个数组中,并返回一个新数组。  
  158.      * @param array被添加到的数组  
  159.      * @param object 被添加的object  
  160.      * @return T[] 返回的新数组  
  161.      */  
  162.     public static <T> T[] addObjectToArray(T[] array, T obj) {  
  163.         //结果数组  
  164.         T[] resArray=null;  
  165.         if (isEmpty(array)) {  
  166.             resArray=(T[])java.lang.reflect.Array.newInstance(obj.getClass(), 1);  
  167.             resArray[0]=obj;  
  168.             return resArray;  
  169.         }  
  170.         //原数组不为空时。  
  171.         resArray=(T[])java.lang.reflect.Array.newInstance(array[0].getClass(), array.length+1);  
  172.         System.arraycopy(array, 0, resArray, 0, array.length);  
  173.         resArray[array.length] = obj;  
  174.         return resArray;  
  175.     }  
  176.       
  177.     /**  
  178.      * 功能:判断数组是不是空。(null或者length==0)  
  179.       * @author 宋立君  
  180.      * @date 2014年06月25日  
  181.      * @param array 数组  
  182.      * @return boolean 空返回true,否则返回false。  
  183.      */  
  184.     public static <T> boolean isEmpty(T[] array) {  
  185.         return (array == null || array.length==0);  
  186.     }  
  187.       
  188.       
  189.     /**  
  190.      * 功能:集合是否为空。如果传入的值为null或者集合不包含元素都认为为空。  
  191.      * @author 宋立君  
  192.      * @date 2014年06月25日  
  193.      * @param collection 集合  
  194.      * @return boolean 为空返回true,否则返回false。  
  195.      */  
  196.     public static boolean isEmpty(Collection collection) {  
  197.         return (collection == null || collection.isEmpty());  
  198.     }  
  199.   
  200.     /**  
  201.      * 功能:Map是否为空。如果传入的值为null或者集合不包含元素都认为为空。  
  202.      * @author 宋立君  
  203.      * @date 2014年06月25日  
  204.      * @param map Map  
  205.      * @return boolean 为空返回true,否则返回false。  
  206.      */  
  207.     public static boolean isEmpty(Map map) {  
  208.         return (map == null || map.isEmpty());  
  209.     }  
  210.       
  211. }  

5 MathUtil代码:

  1. package com.itjh.javaUtil;  
  2.   
  3. import java.math.BigDecimal;  
  4.   
  5. /** 
  6.  * 数学运算辅助类。 
  7.  *  
  8.  * @author 宋立君 
  9.  * @date 2014年06月25日 
  10.  */  
  11. public class MathUtil {  
  12.   
  13.     /** 
  14.      * 功能:将字符串转换为BigDecimal,一般用于数字运算时。 
  15.      *  
  16.      * @author 宋立君 
  17.      * @date 2014年06月25日 
  18.      * @param str 
  19.      *            字符串 
  20.      * @return BigDecimal,str为empty时返回null。 
  21.      */  
  22.     public static BigDecimal toBigDecimal(String str) {  
  23.         if (StringUtil.isEmpty(str)) {  
  24.             return null;  
  25.         }  
  26.         return new BigDecimal(str);  
  27.     }  
  28.   
  29.     /** 
  30.      * 功能:将字符串抓换为double,如果失败返回默认值。 
  31.      *  
  32.      * @author 宋立君 
  33.      * @date 2014年06月25日 
  34.      * @param str 
  35.      *            字符串 
  36.      * @param defaultValue 
  37.      *            失败时返回的默认值 
  38.      * @return double 
  39.      */  
  40.     public static double toDouble(String str, double defaultValue) {  
  41.         if (str == null) {  
  42.             return defaultValue;  
  43.         }  
  44.         try {  
  45.             return Double.parseDouble(str);  
  46.         } catch (NumberFormatException nfe) {  
  47.             return defaultValue;  
  48.         }  
  49.     }  
  50.   
  51.     /** 
  52.      * 功能:将字符串抓换为float,如果失败返回默认值。 
  53.      *  
  54.      * @author 宋立君 
  55.      * @date 2014年06月25日 
  56.      * @param str 
  57.      *            字符串 
  58.      * @param defaultValue 
  59.      *            失败时返回的默认值 
  60.      * @return float 
  61.      */  
  62.     public static float toFloat(String str, float defaultValue) {  
  63.         if (str == null) {  
  64.             return defaultValue;  
  65.         }  
  66.         try {  
  67.             return Float.parseFloat(str);  
  68.         } catch (NumberFormatException nfe) {  
  69.             return defaultValue;  
  70.         }  
  71.     }  
  72.   
  73.     /** 
  74.      * 功能:将字符串抓换为long,如果失败返回默认值。 
  75.      *  
  76.      * @author 宋立君 
  77.      * @date 2014年06月25日 
  78.      * @param str 
  79.      *            字符串 
  80.      * @param defaultValue 
  81.      *            失败时返回的默认值 
  82.      * @return long 
  83.      */  
  84.     public static long toLong(String str, long defaultValue) {  
  85.         if (str == null) {  
  86.             return defaultValue;  
  87.         }  
  88.         try {  
  89.             return Long.parseLong(str);  
  90.         } catch (NumberFormatException nfe) {  
  91.             return defaultValue;  
  92.         }  
  93.     }  
  94.   
  95.     /** 
  96.      * 功能:将字符串抓换为int,如果失败返回默认值。 
  97.      *  
  98.      * @author 宋立君 
  99.      * @date 2014年06月25日 
  100.      * @param str 
  101.      *            字符串 
  102.      * @param defaultValue 
  103.      *            失败时返回的默认值 
  104.      * @return int 
  105.      */  
  106.     public static int toInt(String str, int defaultValue) {  
  107.         if (str == null) {  
  108.             return defaultValue;  
  109.         }  
  110.         try {  
  111.             return Integer.parseInt(str);  
  112.         } catch (NumberFormatException nfe) {  
  113.             return defaultValue;  
  114.         }  
  115.     }  
  116.   
  117.     /** 
  118.      * <p> 
  119.      * 得到两个 <code>double</code>值中最大的一个. 
  120.      * </p> 
  121.      *  
  122.      * @param a 
  123.      *            值 1 
  124.      * @param b 
  125.      *            值 2 
  126.      * @return 最大的值 
  127.      * @author 宋立君 
  128.      * @date 2014年06月25日 
  129.      */  
  130.     public static float getMax(float a, float b) {  
  131.         if (Float.isNaN(a)) {  
  132.             return b;  
  133.         } else if (Float.isNaN(b)) {  
  134.             return a;  
  135.         } else {  
  136.             return Math.max(a, b);  
  137.         }  
  138.     }  
  139.   
  140.     /** 
  141.      * <p> 
  142.      * 得到数组中最大的一个. 
  143.      * </p> 
  144.      *  
  145.      * @param array 
  146.      *            数组不能为null,也不能为空。 
  147.      * @return 得到数组中最大的一个. 
  148.      * @throws IllegalArgumentException 
  149.      *             如果 <code>数组</code> 是 <code>null</code> 
  150.      * @throws IllegalArgumentException 
  151.      *             如果 <code>数组</code>是空 
  152.      * @author 宋立君 
  153.      * @date 2014年06月25日 
  154.      */  
  155.     public static float getMax(float[] array) {  
  156.         // Validates input  
  157.         if (array == null) {  
  158.             throw new IllegalArgumentException("The Array must not be null");  
  159.         } else if (array.length == 0) {  
  160.             throw new IllegalArgumentException("Array cannot be empty.");  
  161.         }  
  162.   
  163.         // Finds and returns max  
  164.         float max = array[0];  
  165.         for (int j = 1; j < array.length; j++) {  
  166.             max = getMax(array[j], max);  
  167.         }  
  168.   
  169.         return max;  
  170.     }  
  171.   
  172.     /** 
  173.      * <p> 
  174.      * 得到数组中最大的一个. 
  175.      * </p> 
  176.      *  
  177.      * @param array 
  178.      *            数组不能为null,也不能为空。 
  179.      * @return 得到数组中最大的一个. 
  180.      * @throws IllegalArgumentException 
  181.      *             如果 <code>数组</code> 是 <code>null</code> 
  182.      * @throws IllegalArgumentException 
  183.      *             如果 <code>数组</code>是空 
  184.      * @author 宋立君 
  185.      * @date 2014年06月25日 
  186.      */  
  187.     public static double getMax(double[] array) {  
  188.         // Validates input  
  189.         if (array == null) {  
  190.             throw new IllegalArgumentException("The Array must not be null");  
  191.         } else if (array.length == 0) {  
  192.             throw new IllegalArgumentException("Array cannot be empty.");  
  193.         }  
  194.   
  195.         // Finds and returns max  
  196.         double max = array[0];  
  197.         for (int j = 1; j < array.length; j++) {  
  198.             max = getMax(array[j], max);  
  199.         }  
  200.   
  201.         return max;  
  202.     }  
  203.   
  204.     /** 
  205.      * <p> 
  206.      * 得到两个 <code>double</code>值中最大的一个. 
  207.      * </p> 
  208.      *  
  209.      * @param a 
  210.      *            值 1 
  211.      * @param b 
  212.      *            值 2 
  213.      * @return 最大的值 
  214.      * @author 宋立君 
  215.      * @date 2014年06月25日 
  216.      * */  
  217.     public static double getMax(double a, double b) {  
  218.         if (Double.isNaN(a)) {  
  219.             return b;  
  220.         } else if (Double.isNaN(b)) {  
  221.             return a;  
  222.         } else {  
  223.             return Math.max(a, b);  
  224.         }  
  225.     }  
  226.   
  227.     /** 
  228.      * <p> 
  229.      * 得到两个float中最小的一个。 
  230.      * </p> 
  231.      *  
  232.      * @param a 
  233.      *            值 1 
  234.      * @param b 
  235.      *            值 2 
  236.      * @return double值最小的 
  237.      * @author 宋立君 
  238.      * @date 2014年06月25日 
  239.      */  
  240.     public static float getMin(float a, float b) {  
  241.         if (Float.isNaN(a)) {  
  242.             return b;  
  243.         } else if (Float.isNaN(b)) {  
  244.             return a;  
  245.         } else {  
  246.             return Math.min(a, b);  
  247.         }  
  248.     }  
  249.   
  250.     /** 
  251.      * <p> 
  252.      * 返回数组中最小的数值。 
  253.      * </p> 
  254.      *  
  255.      * @param array 
  256.      *            数组不能为null,也不能为空。 
  257.      * @return 数组里面最小的float 
  258.      * @throws IllegalArgumentException 
  259.      *             如果<code>数组</code>是<code>null</code> 
  260.      * @throws IllegalArgumentException 
  261.      *             如果<code>数组</code>是空 
  262.      * @author 宋立君 
  263.      * @date 2014年06月25日 
  264.      */  
  265.     public static float getMin(float[] array) {  
  266.         // Validates input  
  267.         if (array == null) {  
  268.             throw new IllegalArgumentException("数组不能为null。");  
  269.         } else if (array.length == 0) {  
  270.             throw new IllegalArgumentException("数组不能为空。");  
  271.         }  
  272.   
  273.         // Finds and returns min  
  274.         float min = array[0];  
  275.         for (int i = 1; i < array.length; i++) {  
  276.             min = getMin(array[i], min);  
  277.         }  
  278.   
  279.         return min;  
  280.     }  
  281.   
  282.     /** 
  283.      * <p> 
  284.      * 返回数组中最小的double。 
  285.      * </p> 
  286.      *  
  287.      * @param array 
  288.      *            数组不能为null,也不能为空。 
  289.      * @return 数组里面最小的double 
  290.      * @throws IllegalArgumentException 
  291.      *             如果<code>数组</code>是<code>null</code> 
  292.      * @throws IllegalArgumentException 
  293.      *             如果<code>数组</code>是空 
  294.      * @author 宋立君 
  295.      * @date 2014年06月25日 
  296.      */  
  297.     public static double getMin(double[] array) {  
  298.         // Validates input  
  299.         if (array == null) {  
  300.             throw new IllegalArgumentException("数组不能为null。");  
  301.         } else if (array.length == 0) {  
  302.             throw new IllegalArgumentException("数组不能为空。");  
  303.         }  
  304.         // Finds and returns min  
  305.         double min = array[0];  
  306.         for (int i = 1; i < array.length; i++) {  
  307.             min = getMin(array[i], min);  
  308.         }  
  309.         return min;  
  310.     }  
  311.   
  312.     /** 
  313.      * <p> 
  314.      * 得到两个double中最小的一个。 
  315.      * </p> 
  316.      *  
  317.      * @param a 
  318.      *            值 1 
  319.      * @param b 
  320.      *            值 2 
  321.      * @return double值最小的 
  322.      * @author 宋立君 
  323.      * @date 2014年06月25日 
  324.      */  
  325.     public static double getMin(double a, double b) {  
  326.         if (Double.isNaN(a)) {  
  327.             return b;  
  328.         } else if (Double.isNaN(b)) {  
  329.             return a;  
  330.         } else {  
  331.             return Math.min(a, b);  
  332.         }  
  333.     }  
  334.   
  335.     /** 
  336.      * 返回两个double的商 first除以second。 
  337.      *  
  338.      * @param first 
  339.      *            第一个double 
  340.      * @param second 
  341.      *            第二个double 
  342.      * @return double 
  343.      * @author 宋立君 
  344.      * @date 2014年06月25日 
  345.      */  
  346.     public static double divideDouble(double first, double second) {  
  347.         BigDecimal b1 = new BigDecimal(first);  
  348.         BigDecimal b2 = new BigDecimal(second);  
  349.         return b1.divide(b2).doubleValue();  
  350.     }  
  351.   
  352.     /** 
  353.      * 返回两个double的乘积 first*second。 
  354.      *  
  355.      * @param first 
  356.      *            第一个double 
  357.      * @param second 
  358.      *            第二个double 
  359.      * @return double 
  360.      * @author 宋立君 
  361.      * @date 2014年06月25日 
  362.      */  
  363.     public static double multiplyDouble(double first, double second) {  
  364.         BigDecimal b1 = new BigDecimal(first);  
  365.         BigDecimal b2 = new BigDecimal(second);  
  366.         return b1.multiply(b2).doubleValue();  
  367.     }  
  368.   
  369.     /** 
  370.      * 返回两个double的差值 first-second。 
  371.      *  
  372.      * @param first 
  373.      *            第一个double 
  374.      * @param second 
  375.      *            第二个double 
  376.      * @return double 
  377.      * @author 宋立君 
  378.      * @date 2014年06月25日 
  379.      */  
  380.     public static double subtractDouble(double first, double second) {  
  381.         BigDecimal b1 = new BigDecimal(first);  
  382.         BigDecimal b2 = new BigDecimal(second);  
  383.         return b1.subtract(b2).doubleValue();  
  384.     }  
  385.   
  386.     /** 
  387.      * 返回两个double的和值 first+second。 
  388.      *  
  389.      * @param first 
  390.      *            第一个double 
  391.      * @param second 
  392.      *            第二个double 
  393.      * @return double 
  394.      * @author 宋立君 
  395.      * @date 2014年06月25日 
  396.      */  
  397.     public static double sumDouble(double first, double second) {  
  398.         BigDecimal b1 = new BigDecimal(first);  
  399.         BigDecimal b2 = new BigDecimal(second);  
  400.         return b1.add(b2).doubleValue();  
  401.     }  
  402.   
  403.     /** 
  404.      * 格式化double指定位数小数。例如将11.123格式化为11.1。 
  405.      *  
  406.      * @param value 
  407.      *            原double数字。 
  408.      * @param decimals 
  409.      *            小数位数。 
  410.      * @return 格式化后的double,注意为硬格式化不存在四舍五入。 
  411.      * @author 宋立君 
  412.      * @date 2014年06月25日 
  413.      */  
  414.     public static String formatDouble(double value, int decimals) {  
  415.         String doubleStr = "" + value;  
  416.         int index = doubleStr.indexOf(".") != -1 ? doubleStr.indexOf(".")  
  417.                 : doubleStr.indexOf(",");  
  418.         // Decimal point can not be found...  
  419.         if (index == -1)  
  420.             return doubleStr;  
  421.         // Truncate all decimals  
  422.         if (decimals == 0) {  
  423.             return doubleStr.substring(0, index);  
  424.         }  
  425.         int len = index + decimals + 1;  
  426.         if (len >= doubleStr.length())  
  427.             len = doubleStr.length();  
  428.         double d = Double.parseDouble(doubleStr.substring(0, len));  
  429.         return String.valueOf(d);  
  430.     }  
  431.   
  432.     /** 
  433.      * 生成一个指定位数的随机数,并将其转换为字符串作为函数的返回值。 
  434.      *  
  435.      * @param numberLength 
  436.      *            随机数的位数。 
  437.      * @return String 注意随机数可能以0开头。 
  438.      * @author 宋立君 
  439.      * @date 2014年06月25日 
  440.      */  
  441.     public static String randomNumber(int numberLength) {  
  442.         // 记录生成的每一位随机数  
  443.         StringBuffer sb = new StringBuffer();  
  444.         for (int i = 0; i < numberLength; i++) {  
  445.             // 每次生成一位,随机生成一个0-10之间的随机数,不含10。  
  446.             Double ranDouble = Math.floor(Math.random() * 10);  
  447.             sb.append(ranDouble.intValue());  
  448.         }  
  449.         return sb.toString();  
  450.     }  
  451.   
  452.     /** 
  453.      * 功能:生成一个在最大数和最小数之间的随机数。会出现最小数,但不会出现最大数。 
  454.      *  
  455.      * @author 宋立君 
  456.      * @date 2014年06月25日 
  457.      * @param minNum 
  458.      *            最小数 
  459.      * @param maxNum 
  460.      *            最大数 
  461.      * @return int 
  462.      */  
  463.     public static int randomNumber(int minNum, int maxNum) {  
  464.         if (maxNum <= minNum) {  
  465.             throw new RuntimeException("maxNum必须大于minNum!");  
  466.         }  
  467.         // 计算出来差值  
  468.         int subtract = maxNum - minNum;  
  469.         Double ranDouble = Math.floor(Math.random() * subtract);  
  470.         return ranDouble.intValue() + minNum;  
  471.     }  
  472.   
  473.     /** 
  474.      * 功能:生成一个在最大数和最小数之间的随机数。会出现最小数,但不会出现最大数。<br/> 
  475.      * 但不随机notin数组中指定的数字, 如果可随机的范围较小,可能会一直随机不到,或者随机的很慢。 
  476.      *  
  477.      * @author 宋立君 
  478.      * @date 2014年06月25日 
  479.      * @param minNum 
  480.      *            最小数 
  481.      * @param maxNum 
  482.      *            最大数 
  483.      * @param notin 
  484.      *            不随机数组这些数字 
  485.      * @return int 
  486.      */  
  487.     public static int randomNumber(int minNum, int maxNum, Integer[] notin) {  
  488.         if (notin.length >= (maxNum - minNum)) {  
  489.             throw new RuntimeException("notin数组的元素已经把可以随机的都排除了,无法得到随机数!");  
  490.         }  
  491.         while (true) {  
  492.             int num = randomNumber(minNum, maxNum);  
  493.             if (!CollectionUtil.arrayContain(notin, num)) {  
  494.                 return num;  
  495.             }  
  496.         }  
  497.     }  


原文地址:https://www.cnblogs.com/archermeng/p/7537610.html