您的位置:首页 > 编程语言 > Java开发

java常用工具类(二)

2015-10-09 12:04 666 查看
1、FtpUtil

[java]
view plaincopyprint?





package com.itjh.javaUtil;  
  
import java.io.File;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.OutputStream;  
import java.util.ArrayList;  
import java.util.List;  
  
import org.apache.commons.net.ftp.FTPClient;  
import org.apache.commons.net.ftp.FTPFile;  
import org.apache.commons.net.ftp.FTPReply;  
  
/** 
 * 用来操作ftp的综合类。<br/> 
 * 主要依赖jar包commons-net-3.1.jar。 
 *  
 * @author 宋立君 
 * @date 2014年06月25日 
 */  
public class FtpUtil {  
    // ftp 地址  
    private String url;  
    // ftp端口  
    private int port;  
    // 用户名  
    private String userName;  
    // 密码  
    private String password;  
  
    /** 
     * 构造函数 
     *  
     * @param url 
     *            ftp地址 
     * @param port 
     *            ftp端口 
     * @param userName 
     *            用户名 
     * @param password 
     *            密码 
     * @author 宋立君 
     * @date 2014年06月25日 
     * 
     */  
    public FtpUtil(String url, int port, String userName, String password) {  
        this.url = url;  
        this.port = port;  
        this.userName = userName;  
        this.password = password;  
    }  
  
    /** 
     * 从FTP服务器下载指定文件名的文件。 
     *  
     * @param remotePath 
     *            FTP服务器上的相对路径 
     * @param fileName 
     *            要下载的文件名 
     * @param localPath 
     *            下载后保存到本地的路径 
     * @return 成功下载返回true,否则返回false。 
     * @throws IOException 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public boolean downFile(String remotePath, String fileName, String localPath)  
            throws IOException {  
        boolean success = false;  
        FTPClient ftp = new FTPClient();  
        try {  
            int reply;  
            ftp.connect(url, port);  
            // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
            ftp.login(userName, password);// 登录  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                return success;  
            }  
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  
            FTPFile[] fs = ftp.listFiles();  
            FTPFile ff;  
            for (int i = 0; i < fs.length; i++) {  
                ff = fs[i];  
                if (null != ff && null != ff.getName()  
                        && ff.getName().equals(fileName)) {  
                    File localFile = new File(localPath + "/" + ff.getName());  
                    OutputStream is = new FileOutputStream(localFile);  
                    ftp.retrieveFile(ff.getName(), is);  
                    is.close();  
                }  
            }  
            ftp.logout();  
            success = true;  
        } catch (IOException e) {  
            e.printStackTrace();  
            throw e;  
        } finally {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch (IOException ioe) {  
                }  
            }  
        }  
        return success;  
    }  
  
    /** 
     * 从FTP服务器列出指定文件夹下文件名列表。 
     *  
     * @param remotePath 
     *            FTP服务器上的相对路径 
     * @return List<String> 文件名列表,如果出现异常返回null。 
     * @throws IOException 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public List<String> getFileNameList(String remotePath) throws IOException {  
        // 目录列表记录  
        List<String> fileNames = new ArrayList<String>();  
        FTPClient ftp = new FTPClient();  
        try {  
            int reply;  
            ftp.connect(url, port);  
            // 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器  
            ftp.login(userName, password);// 登录  
            reply = ftp.getReplyCode();  
            if (!FTPReply.isPositiveCompletion(reply)) {  
                ftp.disconnect();  
                return null;  
            }  
            ftp.changeWorkingDirectory(remotePath);// 转移到FTP服务器目录  
            FTPFile[] fs = ftp.listFiles();  
            for (FTPFile file : fs) {  
                fileNames.add(file.getName());  
            }  
            ftp.logout();  
        } catch (IOException e) {  
            e.printStackTrace();  
            throw e;  
        } finally {  
            if (ftp.isConnected()) {  
                try {  
                    ftp.disconnect();  
                } catch (IOException ioe) {  
                }  
            }  
        }  
        return fileNames;  
    }  
  
}  

2、 汉字转拼音

[java]
view plaincopyprint?





package com.itjh.test;  
  
import net.sourceforge.pinyin4j.PinyinHelper;  
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;  
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;  
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;  
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;  
  
  
public class SpellHelper {  
     //将中文转换为英文  
     public static String getEname(String name) {  
           HanyuPinyinOutputFormat pyFormat = new HanyuPinyinOutputFormat();  
           pyFormat.setCaseType(HanyuPinyinCaseType. LOWERCASE);  
          pyFormat.setToneType(HanyuPinyinToneType. WITHOUT_TONE);  
           pyFormat.setVCharType(HanyuPinyinVCharType. WITH_V);  
  
            return PinyinHelper. toHanyuPinyinString(name, pyFormat, "");  
     }  
  
     //姓、名的第一个字母需要为大写  
     public static String getUpEname(String name) {  
            char[] strs = name.toCharArray();  
           String newname = null;  
                 
        //名字的长度  
     if (strs.length == 2) {     
                newname = toUpCase(getEname ("" + strs[0])) + " "  
                           + toUpCase(getEname ("" + strs[1]));  
           } else if (strs. length == 3) {  
                newname = toUpCase(getEname ("" + strs[0])) + " "  
                           + toUpCase(getEname ("" + strs[1] + strs[2]));  
           } else if (strs. length == 4) {  
                newname = toUpCase(getEname ("" + strs[0] + strs[1])) + " "  
                           + toUpCase(getEname ("" + strs[2] + strs[3]));  
           } else {  
                newname = toUpCase(getEname (name));  
           }  
  
            return newname;  
     }  
  
     //首字母大写  
     private static String toUpCase(String str) {  
           StringBuffer newstr = new StringBuffer();  
           newstr.append((str.substring(0, 1)).toUpperCase()).append(  
                     str.substring(1, str.length()));  
  
            return newstr.toString();  
     }  
  
     public static void main(String[] args) {  
           System. out.println( getEname("李宇春"));  
  
     }  
  
}  

3、zip工具类

[java]
view plaincopyprint?





package com.itjh.javaUtil;  
  
import java.io.BufferedInputStream;  
import java.io.BufferedOutputStream;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileOutputStream;  
import java.io.IOException;  
import java.io.InputStream;  
import java.io.OutputStream;  
import java.util.Enumeration;  
  
import org.apache.commons.compress.archivers.zip.Zip64Mode;  
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;  
import org.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;  
import org.apache.commons.compress.archivers.zip.ZipFile;  
import org.apache.commons.compress.utils.IOUtils;  
  
/** 
 * Zip工具栏类,依赖于commons-compress-1.5.jar。 
 *  
 * @author 宋立君 
 * @date 2014年06月25日 
 */  
public class ZipUtil {  
  
    // public static void main(String[] args){  
    // try {  
    // //new ZipUtil().decompressZip(new  
    // File("d://img.zip"),"img/pic20140626.jpg","d://");  
    // new ZipUtil().decompressZip(new File("d://img.zip"),"flight.log","d://");  
    // //new File("d://flight.log").delete();  
    // //ZipUtil.compress(new File("D://测试压缩文件"),new File("d://img.zip"));  
    // // ZipUtil.compress(new File[]{new  
    // File("F:/testZIP/testzip.txt"),new File("d://ftp"),new  
    // File("e://ftp")},new File("d://压缩文件.zip"));  
    // } catch (IOException e) {  
    // e.printStackTrace();  
    // }  
    // }  
  
    /** 
     * 把N多文件或文件夹压缩成zip。 
     *  
     * @param files 
     *            需要压缩的文件或文件夹。 
     * @param zipFilePath 
     *            压缩后的zip文件 
     * @throws IOException 
     *             压缩时IO异常。 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static void compress(File[] files, File zipFile) throws IOException {  
        if (CollectionUtil.isEmpty(files)) {  
            return;  
        }  
        ZipArchiveOutputStream out = new ZipArchiveOutputStream(zipFile);  
        out.setUseZip64(Zip64Mode.AsNeeded);  
        // 将每个文件用ZipArchiveEntry封装  
        for (File file : files) {  
            if (file == null) {  
                continue;  
            }  
            compressOneFile(file, out, "");  
        }  
        if (out != null) {  
            out.close();  
        }  
    }  
  
    /** 
     * 功能:压缩文件或文件夹。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param srcFile 
     *            源文件。 
     * @param destFile 
     *            压缩后的文件 
     * @throws IOException 
     *             压缩时出现了异常。 
     */  
    public static void compress(File srcFile, File destFile) throws IOException {  
        ZipArchiveOutputStream out = null;  
        try {  
            out = new ZipArchiveOutputStream(new BufferedOutputStream(  
                    new FileOutputStream(destFile), 1024));  
            compressOneFile(srcFile, out, "");  
        } finally {  
            out.close();  
        }  
    }  
  
    /** 
     * 功能:压缩单个文件,非文件夹。私有,不对外开放。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param srcFile 
     *            源文件,不能是文件夹。 
     * @param out 
     *            压缩文件的输出流。 
     * @param destFile 
     *            压缩后的文件 
     * @param dir 
     *            在压缩包中的位置,根目录传入/。 
     * @throws IOException 
     *             压缩时出现了异常。 
     */  
    private static void compressOneFile(File srcFile,  
            ZipArchiveOutputStream out, String dir) throws IOException {  
        if (srcFile.isDirectory()) {// 对文件夹进行处理。  
            ZipArchiveEntry entry = new ZipArchiveEntry(dir + srcFile.getName()  
                    + "/");  
            out.putArchiveEntry(entry);  
            out.closeArchiveEntry();  
            // 循环文件夹中的所有文件进行压缩处理。  
            String[] subFiles = srcFile.list();  
            for (String subFile : subFiles) {  
                compressOneFile(new File(srcFile.getPath() + "/" + subFile),  
                        out, (dir + srcFile.getName() + "/"));  
            }  
        } else { // 普通文件。  
            InputStream is = null;  
            try {  
                is = new BufferedInputStream(new FileInputStream(srcFile));  
                // 创建一个压缩包。  
                ZipArchiveEntry entry = new ZipArchiveEntry(srcFile, dir  
                        + srcFile.getName());  
                out.putArchiveEntry(entry);  
                IOUtils.copy(is, out);  
                out.closeArchiveEntry();  
            } finally {  
                if (is != null)  
                    is.close();  
            }  
        }  
    }  
  
    /** 
     * 功能:解压缩zip压缩包下的所有文件。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param zipFile 
     *            zip压缩文件 
     * @param dir 
     *            解压缩到这个路径下 
     * @throws IOException 
     *             文件流异常 
     */  
    public void decompressZip(File zipFile, String dir) throws IOException {  
        ZipFile zf = new ZipFile(zipFile);  
        try {  
            for (Enumeration<ZipArchiveEntry> entries = zf.getEntries(); entries  
                    .hasMoreElements();) {  
                ZipArchiveEntry ze = entries.nextElement();  
                // 不存在则创建目标文件夹。  
                File targetFile = new File(dir, ze.getName());  
                // 遇到根目录时跳过。  
                if (ze.getName().lastIndexOf("/") == (ze.getName().length() - 1)) {  
                    continue;  
                }  
                // 如果文件夹不存在,创建文件夹。  
                if (!targetFile.getParentFile().exists()) {  
                    targetFile.getParentFile().mkdirs();  
                }  
  
                InputStream i = zf.getInputStream(ze);  
                OutputStream o = null;  
                try {  
                    o = new FileOutputStream(targetFile);  
                    IOUtils.copy(i, o);  
                } finally {  
                    if (i != null) {  
                        i.close();  
                    }  
                    if (o != null) {  
                        o.close();  
                    }  
                }  
            }  
        } finally {  
            zf.close();  
        }  
    }  
  
    /** 
     * 功能:解压缩zip压缩包下的某个文件信息。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param zipFile 
     *            zip压缩文件 
     * @param fileName 
     *            某个文件名,例如abc.zip下面的a.jpg,需要传入/abc/a.jpg。 
     * @param dir 
     *            解压缩到这个路径下 
     * @throws IOException 
     *             文件流异常 
     */  
    public void decompressZip(File zipFile, String fileName, String dir)  
            throws IOException {  
        // 不存在则创建目标文件夹。  
        File targetFile = new File(dir, fileName);  
        if (!targetFile.getParentFile().exists()) {  
            targetFile.getParentFile().mkdirs();  
        }  
  
        ZipFile zf = new ZipFile(zipFile);  
        Enumeration<ZipArchiveEntry> zips = zf.getEntries();  
        ZipArchiveEntry zip = null;  
        while (zips.hasMoreElements()) {  
            zip = zips.nextElement();  
            if (fileName.equals(zip.getName())) {  
                OutputStream o = null;  
                InputStream i = zf.getInputStream(zip);  
                try {  
                    o = new FileOutputStream(targetFile);  
                    IOUtils.copy(i, o);  
                } finally {  
                    if (i != null) {  
                        i.close();  
                    }  
                    if (o != null) {  
                        o.close();  
                    }  
                }  
            }  
        }  
    }  
  
    /** 
     * 功能:得到zip压缩包下的某个文件信息,只能在根目录下查找。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param zipFile 
     *            zip压缩文件 
     * @param fileName 
     *            某个文件名,例如abc.zip下面的a.jpg,需要传入/abc/a.jpg。 
     * @return ZipArchiveEntry 压缩文件中的这个文件,没有找到返回null。 
     * @throws IOException 
     *             文件流异常 
     */  
    public ZipArchiveEntry readZip(File zipFile, String fileName)  
            throws IOException {  
        ZipFile zf = new ZipFile(zipFile);  
        Enumeration<ZipArchiveEntry> zips = zf.getEntries();  
        ZipArchiveEntry zip = null;  
        while (zips.hasMoreElements()) {  
            zip = zips.nextElement();  
            if (fileName.equals(zip.getName())) {  
                return zip;  
            }  
        }  
        return null;  
    }  
  
    /** 
     * 功能:得到zip压缩包下的所有文件信息。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param zipFile 
     *            zip压缩文件 
     * @return Enumeration<ZipArchiveEntry> 压缩文件中的文件枚举。 
     * @throws IOException 
     *             文件流异常 
     */  
    public Enumeration<ZipArchiveEntry> readZip(File zipFile)  
            throws IOException {  
        ZipFile zf = new ZipFile(zipFile);  
        Enumeration<ZipArchiveEntry> zips = zf.getEntries();  
        return zips;  
    }  
}  

4 CollectionUtil代码:

[html]
view plaincopyprint?





package com.itjh.javaUtil;  
  
import java.util.Collection;  
import java.util.LinkedList;  
import java.util.List;  
import java.util.Map;  
  
/**  
 * 集合(List,Map,Set)辅助类。  
 * @author 宋立君  
 * @date 2014年06月25日  
 */  
public class CollectionUtil {  
      
    /**  
     * 功能:从List中随机取出一个元素。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param objs 源List  
     * @return T List的一个元素  
     */  
    public static <T> T randomOne(List<T> list){  
        if(isEmpty(list)){  
            return null;  
        }  
        return list.get(MathUtil.randomNumber(0, list.size()));  
    }  
      
    /**  
     * 功能:从数组中随机取出一个元素。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param objs 源数组  
     * @return T 数组的一个元素  
     */  
    public static <T> T randomOne(T[] objs){  
        if(isEmpty(objs)){  
            return null;  
        }  
        return objs[MathUtil.randomNumber(0, objs.length)];  
    }  
      
    /**  
     * 功能:数组中是否存在这个元素。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param objArr 数组  
     * @param compare 元素  
     * @return 存在返回true,否则返回false。  
     */  
    public static <T> boolean arrayContain(T[] objArr,T compare){  
        if(isEmpty(objArr)){  
            return false;  
        }  
        for(T obj : objArr){  
            if(obj.equals(compare)){  
                return true;  
            }  
        }  
        return false;  
    }  
      
  
    /**  
     * 功能:向list中添加数组。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param list List  
     * @param array 数组  
     */  
    public static <T> void addArrayToList(List<T> list, T[] array) {  
        if (isEmpty(list)) {  
            return;  
        }  
        for (T t : array) {  
            list.add(t);  
        }  
    }  
      
    /**  
     * 功能:将数组进行反转,倒置。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param objs 源数组  
     * @return T[] 反转后的数组  
     */  
    public static <T> T[] reverseArray(T[] objs){  
        if(isEmpty(objs)){  
            return null;  
        }  
        T[] res=(T[])java.lang.reflect.Array.newInstance(objs[0].getClass(), objs.length);  
        //新序号  
        int k=0;  
        for(int i=objs.length-1 ; i>=0 ; i--){  
            res[k++]=objs[i];  
        }  
        return res;  
    }  
      
    /**  
     * 功能:将数组转为list。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param objs 源数组  
     * @return List  
     */  
    public static <T> List<T> arrayToList(T[] objs){  
        if(isEmpty(objs)){  
            return null;  
        }  
        List<T> list=new LinkedList<T>();  
        for(T obj : objs){  
            list.add(obj);  
        }  
        return list;  
    }  
      
    /**  
     * 功能:将list转为数组。  
      * @author 宋立君  
     * @date 2014年06月25日  
     * @param list 源list  
     * @return T[]  
     */  
    public static <T> T[] listToArray(List<T> list){  
        if(isEmpty(list)){  
            return null;  
        }  
        T[] objs=(T[])java.lang.reflect.Array.newInstance(list.get(0).getClass(), list.size());  
        int i=0; //数组下标。  
        for(T obj : list){  
            objs[i++]=obj;  
        }  
        return objs;  
    }  
      
    /**  
     * 将一个字符串数组的内容全部添加到另外一个数组中,并返回一个新数组。  
     * @param array1 第一个数组  
     * @param array2 第二个数组  
     * @return T[] 拼接后的新数组  
     */  
    public static <T> T[] concatenateArrays(T[] array1, T[] array2) {  
        if (isEmpty(array1)) {  
            return array2;  
        }  
        if (isEmpty(array2)) {  
            return array1;  
        }  
        T[] resArray=(T[])java.lang.reflect.Array.newInstance(array1[0].getClass(), array1.length+array2.length);  
        System.arraycopy(array1, 0, resArray, 0, array1.length);  
        System.arraycopy(array2, 0, resArray, array1.length, array2.length);  
        return resArray;  
    }  
      
    /**  
     * 将一个object添加到一个数组中,并返回一个新数组。  
     * @param array被添加到的数组  
     * @param object 被添加的object  
     * @return T[] 返回的新数组  
     */  
    public static <T> T[] addObjectToArray(T[] array, T obj) {  
        //结果数组  
        T[] resArray=null;  
        if (isEmpty(array)) {  
            resArray=(T[])java.lang.reflect.Array.newInstance(obj.getClass(), 1);  
            resArray[0]=obj;  
            return resArray;  
        }  
        //原数组不为空时。  
        resArray=(T[])java.lang.reflect.Array.newInstance(array[0].getClass(), array.length+1);  
        System.arraycopy(array, 0, resArray, 0, array.length);  
        resArray[array.length] = obj;  
        return resArray;  
    }  
      
    /**  
     * 功能:判断数组是不是空。(null或者length==0)  
      * @author 宋立君  
     * @date 2014年06月25日  
     * @param array 数组  
     * @return boolean 空返回true,否则返回false。  
     */  
    public static <T> boolean isEmpty(T[] array) {  
        return (array == null || array.length==0);  
    }  
      
      
    /**  
     * 功能:集合是否为空。如果传入的值为null或者集合不包含元素都认为为空。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param collection 集合  
     * @return boolean 为空返回true,否则返回false。  
     */  
    public static boolean isEmpty(Collection collection) {  
        return (collection == null || collection.isEmpty());  
    }  
  
    /**  
     * 功能:Map是否为空。如果传入的值为null或者集合不包含元素都认为为空。  
     * @author 宋立君  
     * @date 2014年06月25日  
     * @param map Map  
     * @return boolean 为空返回true,否则返回false。  
     */  
    public static boolean isEmpty(Map map) {  
        return (map == null || map.isEmpty());  
    }  
      
}  

5 MathUtil代码:

[java]
view plaincopyprint?





package com.itjh.javaUtil;  
  
import java.math.BigDecimal;  
  
/** 
 * 数学运算辅助类。 
 *  
 * @author 宋立君 
 * @date 2014年06月25日 
 */  
public class MathUtil {  
  
    /** 
     * 功能:将字符串转换为BigDecimal,一般用于数字运算时。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param str 
     *            字符串 
     * @return BigDecimal,str为empty时返回null。 
     */  
    public static BigDecimal toBigDecimal(String str) {  
        if (StringUtil.isEmpty(str)) {  
            return null;  
        }  
        return new BigDecimal(str);  
    }  
  
    /** 
     * 功能:将字符串抓换为double,如果失败返回默认值。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param str 
     *            字符串 
     * @param defaultValue 
     *            失败时返回的默认值 
     * @return double 
     */  
    public static double toDouble(String str, double defaultValue) {  
        if (str == null) {  
            return defaultValue;  
        }  
        try {  
            return Double.parseDouble(str);  
        } catch (NumberFormatException nfe) {  
            return defaultValue;  
        }  
    }  
  
    /** 
     * 功能:将字符串抓换为float,如果失败返回默认值。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param str 
     *            字符串 
     * @param defaultValue 
     *            失败时返回的默认值 
     * @return float 
     */  
    public static float toFloat(String str, float defaultValue) {  
        if (str == null) {  
            return defaultValue;  
        }  
        try {  
            return Float.parseFloat(str);  
        } catch (NumberFormatException nfe) {  
            return defaultValue;  
        }  
    }  
  
    /** 
     * 功能:将字符串抓换为long,如果失败返回默认值。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param str 
     *            字符串 
     * @param defaultValue 
     *            失败时返回的默认值 
     * @return long 
     */  
    public static long toLong(String str, long defaultValue) {  
        if (str == null) {  
            return defaultValue;  
        }  
        try {  
            return Long.parseLong(str);  
        } catch (NumberFormatException nfe) {  
            return defaultValue;  
        }  
    }  
  
    /** 
     * 功能:将字符串抓换为int,如果失败返回默认值。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param str 
     *            字符串 
     * @param defaultValue 
     *            失败时返回的默认值 
     * @return int 
     */  
    public static int toInt(String str, int defaultValue) {  
        if (str == null) {  
            return defaultValue;  
        }  
        try {  
            return Integer.parseInt(str);  
        } catch (NumberFormatException nfe) {  
            return defaultValue;  
        }  
    }  
  
    /** 
     * <p> 
     * 得到两个 <code>double</code>值中最大的一个. 
     * </p> 
     *  
     * @param a 
     *            值 1 
     * @param b 
     *            值 2 
     * @return 最大的值 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static float getMax(float a, float b) {  
        if (Float.isNaN(a)) {  
            return b;  
        } else if (Float.isNaN(b)) {  
            return a;  
        } else {  
            return Math.max(a, b);  
        }  
    }  
  
    /** 
     * <p> 
     * 得到数组中最大的一个. 
     * </p> 
     *  
     * @param array 
     *            数组不能为null,也不能为空。 
     * @return 得到数组中最大的一个. 
     * @throws IllegalArgumentException 
     *             如果 <code>数组</code> 是 <code>null</code> 
     * @throws IllegalArgumentException 
     *             如果 <code>数组</code>是空 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static float getMax(float[] array) {  
        // Validates input  
        if (array == null) {  
            throw new IllegalArgumentException("The Array must not be null");  
        } else if (array.length == 0) {  
            throw new IllegalArgumentException("Array cannot be empty.");  
        }  
  
        // Finds and returns max  
        float max = array[0];  
        for (int j = 1; j < array.length; j++) {  
            max = getMax(array[j], max);  
        }  
  
        return max;  
    }  
  
    /** 
     * <p> 
     * 得到数组中最大的一个. 
     * </p> 
     *  
     * @param array 
     *            数组不能为null,也不能为空。 
     * @return 得到数组中最大的一个. 
     * @throws IllegalArgumentException 
     *             如果 <code>数组</code> 是 <code>null</code> 
     * @throws IllegalArgumentException 
     *             如果 <code>数组</code>是空 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static double getMax(double[] array) {  
        // Validates input  
        if (array == null) {  
            throw new IllegalArgumentException("The Array must not be null");  
        } else if (array.length == 0) {  
            throw new IllegalArgumentException("Array cannot be empty.");  
        }  
  
        // Finds and returns max  
        double max = array[0];  
        for (int j = 1; j < array.length; j++) {  
            max = getMax(array[j], max);  
        }  
  
        return max;  
    }  
  
    /** 
     * <p> 
     * 得到两个 <code>double</code>值中最大的一个. 
     * </p> 
     *  
     * @param a 
     *            值 1 
     * @param b 
     *            值 2 
     * @return 最大的值 
     * @author 宋立君 
     * @date 2014年06月25日 
     * */  
    public static double getMax(double a, double b) {  
        if (Double.isNaN(a)) {  
            return b;  
        } else if (Double.isNaN(b)) {  
            return a;  
        } else {  
            return Math.max(a, b);  
        }  
    }  
  
    /** 
     * <p> 
     * 得到两个float中最小的一个。 
     * </p> 
     *  
     * @param a 
     *            值 1 
     * @param b 
     *            值 2 
     * @return double值最小的 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static float getMin(float a, float b) {  
        if (Float.isNaN(a)) {  
            return b;  
        } else if (Float.isNaN(b)) {  
            return a;  
        } else {  
            return Math.min(a, b);  
        }  
    }  
  
    /** 
     * <p> 
     * 返回数组中最小的数值。 
     * </p> 
     *  
     * @param array 
     *            数组不能为null,也不能为空。 
     * @return 数组里面最小的float 
     * @throws IllegalArgumentException 
     *             如果<code>数组</code>是<code>null</code> 
     * @throws IllegalArgumentException 
     *             如果<code>数组</code>是空 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static float getMin(float[] array) {  
        // Validates input  
        if (array == null) {  
            throw new IllegalArgumentException("数组不能为null。");  
        } else if (array.length == 0) {  
            throw new IllegalArgumentException("数组不能为空。");  
        }  
  
        // Finds and returns min  
        float min = array[0];  
        for (int i = 1; i < array.length; i++) {  
            min = getMin(array[i], min);  
        }  
  
        return min;  
    }  
  
    /** 
     * <p> 
     * 返回数组中最小的double。 
     * </p> 
     *  
     * @param array 
     *            数组不能为null,也不能为空。 
     * @return 数组里面最小的double 
     * @throws IllegalArgumentException 
     *             如果<code>数组</code>是<code>null</code> 
     * @throws IllegalArgumentException 
     *             如果<code>数组</code>是空 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static double getMin(double[] array) {  
        // Validates input  
        if (array == null) {  
            throw new IllegalArgumentException("数组不能为null。");  
        } else if (array.length == 0) {  
            throw new IllegalArgumentException("数组不能为空。");  
        }  
        // Finds and returns min  
        double min = array[0];  
        for (int i = 1; i < array.length; i++) {  
            min = getMin(array[i], min);  
        }  
        return min;  
    }  
  
    /** 
     * <p> 
     * 得到两个double中最小的一个。 
     * </p> 
     *  
     * @param a 
     *            值 1 
     * @param b 
     *            值 2 
     * @return double值最小的 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static double getMin(double a, double b) {  
        if (Double.isNaN(a)) {  
            return b;  
        } else if (Double.isNaN(b)) {  
            return a;  
        } else {  
            return Math.min(a, b);  
        }  
    }  
  
    /** 
     * 返回两个double的商 first除以second。 
     *  
     * @param first 
     *            第一个double 
     * @param second 
     *            第二个double 
     * @return double 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static double divideDouble(double first, double second) {  
        BigDecimal b1 = new BigDecimal(first);  
        BigDecimal b2 = new BigDecimal(second);  
        return b1.divide(b2).doubleValue();  
    }  
  
    /** 
     * 返回两个double的乘积 first*second。 
     *  
     * @param first 
     *            第一个double 
     * @param second 
     *            第二个double 
     * @return double 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static double multiplyDouble(double first, double second) {  
        BigDecimal b1 = new BigDecimal(first);  
        BigDecimal b2 = new BigDecimal(second);  
        return b1.multiply(b2).doubleValue();  
    }  
  
    /** 
     * 返回两个double的差值 first-second。 
     *  
     * @param first 
     *            第一个double 
     * @param second 
     *            第二个double 
     * @return double 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static double subtractDouble(double first, double second) {  
        BigDecimal b1 = new BigDecimal(first);  
        BigDecimal b2 = new BigDecimal(second);  
        return b1.subtract(b2).doubleValue();  
    }  
  
    /** 
     * 返回两个double的和值 first+second。 
     *  
     * @param first 
     *            第一个double 
     * @param second 
     *            第二个double 
     * @return double 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static double sumDouble(double first, double second) {  
        BigDecimal b1 = new BigDecimal(first);  
        BigDecimal b2 = new BigDecimal(second);  
        return b1.add(b2).doubleValue();  
    }  
  
    /** 
     * 格式化double指定位数小数。例如将11.123格式化为11.1。 
     *  
     * @param value 
     *            原double数字。 
     * @param decimals 
     *            小数位数。 
     * @return 格式化后的double,注意为硬格式化不存在四舍五入。 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static String formatDouble(double value, int decimals) {  
        String doubleStr = "" + value;  
        int index = doubleStr.indexOf(".") != -1 ? doubleStr.indexOf(".")  
                : doubleStr.indexOf(",");  
        // Decimal point can not be found...  
        if (index == -1)  
            return doubleStr;  
        // Truncate all decimals  
        if (decimals == 0) {  
            return doubleStr.substring(0, index);  
        }  
        int len = index + decimals + 1;  
        if (len >= doubleStr.length())  
            len = doubleStr.length();  
        double d = Double.parseDouble(doubleStr.substring(0, len));  
        return String.valueOf(d);  
    }  
  
    /** 
     * 生成一个指定位数的随机数,并将其转换为字符串作为函数的返回值。 
     *  
     * @param numberLength 
     *            随机数的位数。 
     * @return String 注意随机数可能以0开头。 
     * @author 宋立君 
     * @date 2014年06月25日 
     */  
    public static String randomNumber(int numberLength) {  
        // 记录生成的每一位随机数  
        StringBuffer sb = new StringBuffer();  
        for (int i = 0; i < numberLength; i++) {  
            // 每次生成一位,随机生成一个0-10之间的随机数,不含10。  
            Double ranDouble = Math.floor(Math.random() * 10);  
            sb.append(ranDouble.intValue());  
        }  
        return sb.toString();  
    }  
  
    /** 
     * 功能:生成一个在最大数和最小数之间的随机数。会出现最小数,但不会出现最大数。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param minNum 
     *            最小数 
     * @param maxNum 
     *            最大数 
     * @return int 
     */  
    public static int randomNumber(int minNum, int maxNum) {  
        if (maxNum <= minNum) {  
            throw new RuntimeException("maxNum必须大于minNum!");  
        }  
        // 计算出来差值  
        int subtract = maxNum - minNum;  
        Double ranDouble = Math.floor(Math.random() * subtract);  
        return ranDouble.intValue() + minNum;  
    }  
  
    /** 
     * 功能:生成一个在最大数和最小数之间的随机数。会出现最小数,但不会出现最大数。<br/> 
     * 但不随机notin数组中指定的数字, 如果可随机的范围较小,可能会一直随机不到,或者随机的很慢。 
     *  
     * @author 宋立君 
     * @date 2014年06月25日 
     * @param minNum 
     *            最小数 
     * @param maxNum 
     *            最大数 
     * @param notin 
     *            不随机数组这些数字 
     * @return int 
     */  
    public static int randomNumber(int minNum, int maxNum, Integer[] notin) {  
        if (notin.length >= (maxNum - minNum)) {  
            throw new RuntimeException("notin数组的元素已经把可以随机的都排除了,无法得到随机数!");  
        }  
        while (true) {  
            int num = randomNumber(minNum, maxNum);  
            if (!CollectionUtil.arrayContain(notin, num)) {  
                return num;  
            }  
        }  
    }  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: