下面继续分享java中常用的一些工具类,希望给大家带来帮助!

1、FtpUtil

Java
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;}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154

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;
    }
}

依赖包下载链接: http://pan.baidu.com/s/1nt7IoTr 密码: r93l

2、 汉字转拼音

Java
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("李宇春"));}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57

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("李宇春"));
     }
}

需要的jar包 pinyin4.jsr

3、zip工具类

Java
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;} }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278

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;
    }
}

依赖包下载链接: http://pan.baidu.com/s/1eQ9YveU 密码: srnn

CollectionUtil代码:

Java
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());}}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211

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());
    }
    
}

MathUtil代码:

Java
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 inputif (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 maxfloat 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 inputif (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 maxdouble 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 inputif (array == null) {throw new IllegalArgumentException("数组不能为null。");} else if (array.length == 0) {throw new IllegalArgumentException("数组不能为空。");}// Finds and returns minfloat 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 inputif (array == null) {throw new IllegalArgumentException("数组不能为null。");} else if (array.length == 0) {throw new IllegalArgumentException("数组不能为空。");}// Finds and returns mindouble 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 decimalsif (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;}}} }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498

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;
            }
        }
    }
}

如果有问题,及时反馈!!

java中常用的工具类(二)FtpUtil, 汉字转拼音,zip工具类,CollectionUtil,MathUtil,相关推荐

  1. php 汉字转拼音类,完善的汉字转拼音php转换类

    办法是利用矩阵,汉字的组成方式是两个ascii字符,一个高位码,一个低位码,界限分别是128-264 64-128 每个汉字拼音最长为8个字符,由此组成二维矩阵进行查询,弊端是无法解决多音字问题 cl ...

  2. java中常用的日期工具类

    java中常用的日期工具类 日期相关的类: package net.yto.ofclacct.core.util;import java.text.ParseException; import jav ...

  3. Java中常用的类,包,接口

    Java中常用的类,包,接口 包名 说明 java.lang 该包提供了Java编程的基础类,例如 Object.Math.String.StringBuffer.System.Thread等,不使用 ...

  4. java中常用的加密工具

    java中常用的加密工具 1. md5加密工具类 public class MD5Utils {private static final String hexDigIts[] = {"0&q ...

  5. java 中常用的类

    java 中常用的类 Math Math 类,包含用于执行基本数学运算的方法 常用API 取整 l  static double abs(double  a) 获取double 的绝对值 l  sta ...

  6. java中常用的包、类、以及包中常用的类、方法、属性----sql和text\swing

    java中常用的包.类.以及包中常用的类.方法.属性 常用的包 java.io.*; java.util.*; java.lang.*; java.sql.*; java.text.*; java.a ...

  7. java中常用API、Scanner类、匿名对象、Random类、ArrayList类、对象数组

    java中常用API: API:Application Programming Interface,应用程序编程接口.Java API是JDK中提供给我们使用的类的说明文档.这些类将底层的代码实现封装 ...

  8. JAVA中常用接口的介绍及使用示例 java lang Comparable

    分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow 也欢迎大家转载本篇文章.分享知识,造福人民,实现我们中华民族伟大复兴! JAVA ...

  9. java 中常用框架、intell idea简单使用、爬虫系统

    学习:http://www.ityouknow.com/spring-boot.html http://blog.didispace.com/spring-boot-learning-1/ ***in ...

最新文章

  1. OC基础回想(十二)协议
  2. 【Android 进程保活】应用进程拉活 ( 系统 Service 机制拉活 | Service 组件 onStartCommand 方法分析 | 源码资源 )
  3. 开始——“运行”命令集
  4. Boost:基于boost::asio的延迟tcp服务器测试程序
  5. 知识点实用梳理:广播地址、10 BASE T、介质访问控制、ATM信元与HTTP状态码
  6. linux双显卡配置_Linux系统怎么配置双显卡?
  7. JAVA Swing 事件监听
  8. array 前端面试题_一则关于js数组的前端面试题
  9. 2020 年,最适合 AI 的 5 种编程语言
  10. SQL查询语句精华 笔记
  11. PostgreSQL技术周刊第17期:PostgreSQL用户应掌握的高级SQL特性
  12. windows7配置java环境变量
  13. 【测试面试题每日一刷】22道接口测试面试题,附答案
  14. python处理ts_python将ts转换成MP4
  15. .vimrc快捷键设置
  16. 力扣刷题 DAY_78 贪心
  17. 致大学计算机老师的一封信,致大学老师的一封信
  18. 解空间树和搜索空间树
  19. visitor 模式
  20. access数据库的用户名和密码的问题

热门文章

  1. 外审员找工作难吗?审核员怎么选择认证机构?
  2. 联想 Win10 输入文字不显示选字框 解决办法
  3. Tkinter保姆级教程(下)
  4. HaaS600物联网开发板学习笔记(二)---轻应用方式让LED闪烁起来
  5. zb怎么做渲染图_美术丨教程:使用ZBrush渲染制作女神的衣物和皮肤
  6. 照片不超过100kb怎么弄?图片怎么压缩到100kb以内?
  7. acw_sc__v2加密参数分析(XX找房、36氪、亿X欧、大TANGs商务)
  8. SpringCloud之Sleuth
  9. 麻省理工学院科学家发现“π星球”:近似地球大小,3.14天公转一圈-1
  10. 【机器学习基础】TP,TN,FP,FN,Precision,Recall,PR曲线,AP,MAP,TPR,FPR,ROC曲线,AUC值等的解释