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

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

2017-05-02 10:24 591 查看
下面继续分享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

packagecom.itjh.javaUtil;

importjava.io.File;

import java.io.FileOutputStream;
importjava.io.IOException;

import java.io.OutputStream;
importjava.util.ArrayList;

import java.util.List;

import org.apache.commons.net.ftp.FTPClient;
importorg.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日

*/
publicclass
FtpUtil{

// ftp 地址
privateString
url;

// ftp端口
privateint
port;

// 用户名
privateString
userName;

// 密码
privateString
password;

/**

* 构造函数
*

* @param url
* ftp地址

* @param port
* ftp端口

* @param userName
* 用户名

* @param password
* 密码

* @author 宋立君
* @date 2014年06月25日

*
*/

publicFtpUtil(Stringurl,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日

*/
publicboolean
downFile(StringremotePath,String
fileName,String
localPath)

throwsIOException
{
booleansuccess
=false;

FTPClient ftp=
newFTPClient();
try{

intreply;
ftp.connect(url,port);

// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器
ftp.login(userName,password);//
登录

reply=
ftp.getReplyCode();
if(!FTPReply.isPositiveCompletion(reply)){

ftp.disconnect();
returnsuccess;

}
ftp.changeWorkingDirectory(remotePath);//
转移到FTP服务器目录

FTPFile[]fs
=ftp.listFiles();
FTPFileff;

for(inti
=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());
OutputStreamis
=new
FileOutputStream(localFile);

ftp.retrieveFile(ff.getName(),is);
is.close();

}
}

ftp.logout();
success=
true;

}catch
(IOExceptione){
e.printStackTrace();

throwe;
}finally
{

if(ftp.isConnected()){
try{

ftp.disconnect();
}catch
(IOExceptionioe){

}
}

}
returnsuccess;

}

/**
* 从FTP服务器列出指定文件夹下文件名列表。

*
* @param remotePath

* FTP服务器上的相对路径
* @return List<String> 文件名列表,如果出现异常返回null。

* @throws IOException
* @author 宋立君

* @date 2014年06月25日
*/

publicList<String>getFileNameList(StringremotePath)throws
IOException{
// 目录列表记录

List<String>fileNames
=new
ArrayList<String>();
FTPClientftp
=new
FTPClient();

try{
intreply;

ftp.connect(url,port);
// 如果采用默认端口,可以使用ftp.connect(url)的方式直接连接FTP服务器

ftp.login(userName,password);//
登录
reply=
ftp.getReplyCode();

if(!FTPReply.isPositiveCompletion(reply)){
ftp.disconnect();

returnnull;
}

ftp.changeWorkingDirectory(remotePath);//
转移到FTP服务器目录
FTPFile[]fs
=ftp.listFiles();

for(FTPFile
file:
fs){
fileNames.add(file.getName());

}
ftp.logout();

}catch
(IOExceptione){
e.printStackTrace();

throwe;
}finally
{

if(ftp.isConnected()){
try{

ftp.disconnect();
}catch
(IOExceptionioe){

}
}

}
returnfileNames;

}

}

依赖包下载链接: 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

packagecom.itjh.test;

importnet.sourceforge.pinyin4j.PinyinHelper;

import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
importnet.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;

import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
importnet.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

public classSpellHelper
{
//将中文转换为英文

publicstatic
StringgetEname(Stringname){
HanyuPinyinOutputFormat
pyFormat=
newHanyuPinyinOutputFormat();

pyFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
pyFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);

pyFormat.setVCharType(HanyuPinyinVCharType.WITH_V);

returnPinyinHelper.toHanyuPinyinString(name,pyFormat,"");
}

//姓、名的第一个字母需要为大写

publicstatic
StringgetUpEname(Stringname){
char[]strs
=name.toCharArray();

Stringnewname
=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]));
}
elseif
(strs.length
==4){

newname=
toUpCase(getEname(""+
strs[0]+
strs[1]))+
" "
+
toUpCase(getEname(""+
strs[2]+
strs[3]));

}else
{
newname=
toUpCase(getEname(name));

}

returnnewname;
}

//首字母大写

privatestatic
StringtoUpCase(Stringstr){
StringBuffer
newstr=
newStringBuffer();

newstr.append((str.substring(0,1)).toUpperCase()).append(
str.substring(1,str.length()));

returnnewstr.toString();

}

publicstatic
voidmain(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

packagecom.itjh.javaUtil;

importjava.io.BufferedInputStream;

import java.io.BufferedOutputStream;
importjava.io.File;

import java.io.FileInputStream;
importjava.io.FileOutputStream;

import java.io.IOException;
importjava.io.InputStream;

import java.io.OutputStream;
importjava.util.Enumeration;

importorg.apache.commons.compress.archivers.zip.Zip64Mode;

import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
importorg.apache.commons.compress.archivers.zip.ZipArchiveOutputStream;

import org.apache.commons.compress.archivers.zip.ZipFile;
importorg.apache.commons.compress.utils.IOUtils;

/**

* Zip工具栏类,依赖于commons-compress-1.5.jar。
*

* @author 宋立君
* @date 2014年06月25日

*/
publicclass
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日
*/

publicstatic
voidcompress(File[]files,File
zipFile)throws
IOException{
if(CollectionUtil.isEmpty(files)){

return;
}

ZipArchiveOutputStreamout
=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

* 压缩时出现了异常。
*/

publicstatic
voidcompress(FilesrcFile,File
destFile)throws
IOException{
ZipArchiveOutputStreamout
=null;

try{
out=
newZipArchiveOutputStream(newBufferedOutputStream(

newFileOutputStream(destFile),1024));
compressOneFile(srcFile,out,"");

}finally
{
out.close();

}
}

/**

* 功能:压缩单个文件,非文件夹。私有,不对外开放。
*

* @author 宋立君
* @date 2014年06月25日

* @param srcFile
* 源文件,不能是文件夹。

* @param out
* 压缩文件的输出流。

* @param destFile
* 压缩后的文件

* @param dir
* 在压缩包中的位置,根目录传入/。

* @throws IOException
* 压缩时出现了异常。

*/
privatestatic
voidcompressOneFile(FilesrcFile,

ZipArchiveOutputStreamout,String
dir)throws
IOException{
if(srcFile.isDirectory()){//
对文件夹进行处理。

ZipArchiveEntry
entry =new
ZipArchiveEntry(dir+
srcFile.getName()
+"/");

out.putArchiveEntry(entry);
out.closeArchiveEntry();

// 循环文件夹中的所有文件进行压缩处理。
String[]subFiles
=srcFile.list();

for(StringsubFile
:subFiles){
compressOneFile(newFile(srcFile.getPath()+
"/"+
subFile),

out,(dir+
srcFile.getName()+
"/"));
}

}else
{// 普通文件。
InputStreamis
=null;

try{
is=
newBufferedInputStream(newFileInputStream(srcFile));

// 创建一个压缩包。
ZipArchiveEntryentry
=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
* 文件流异常

*/
publicvoid
decompressZip(FilezipFile,String
dir)throws
IOException{

ZipFile zf=
newZipFile(zipFile);
try{

for(Enumeration<ZipArchiveEntry>entries
=zf.getEntries();entries
.hasMoreElements();){

ZipArchiveEntryze
=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();

}

InputStreami
=zf.getInputStream(ze);
OutputStreamo
=null;

try{
o=
newFileOutputStream(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
* 文件流异常

*/
publicvoid
decompressZip(FilezipFile,String
fileName,String
dir)

throwsIOException
{
// 不存在则创建目标文件夹。

File targetFile=
newFile(dir,fileName);
if(!targetFile.getParentFile().exists()){

targetFile.getParentFile().mkdirs();
}

ZipFilezf
=new
ZipFile(zipFile);

Enumeration<ZipArchiveEntry>zips
=zf.getEntries();
ZipArchiveEntryzip
=null;

while(zips.hasMoreElements()){
zip=
zips.nextElement();

if(fileName.equals(zip.getName())){
OutputStreamo
=null;

InputStreami
=zf.getInputStream(zip);
try{

o=
newFileOutputStream(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
* 文件流异常

*/
publicZipArchiveEntry
readZip(FilezipFile,String
fileName)

throwsIOException
{
ZipFilezf
=new
ZipFile(zipFile);

Enumeration<ZipArchiveEntry>zips
=zf.getEntries();
ZipArchiveEntryzip
=null;

while(zips.hasMoreElements()){
zip=
zips.nextElement();

if(fileName.equals(zip.getName())){
returnzip;

}
}

returnnull;
}

/**

* 功能:得到zip压缩包下的所有文件信息。
*

* @author 宋立君
* @date 2014年06月25日

* @param zipFile
* zip压缩文件

* @return Enumeration<ZipArchiveEntry> 压缩文件中的文件枚举。
* @throws IOException

* 文件流异常
*/

publicEnumeration<ZipArchiveEntry>readZip(FilezipFile)
throwsIOException
{

ZipFile zf=
newZipFile(zipFile);
Enumeration<ZipArchiveEntry>zips
=zf.getEntries();

returnzips;
}

}

依赖包下载链接: 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

packagecom.itjh.javaUtil;

importjava.util.Collection;

import java.util.LinkedList;
importjava.util.List;

import java.util.Map;

/**
* 集合(List,Map,Set)辅助类。

* @author 宋立君
* @date 2014年06月25日

*/
publicclass
CollectionUtil{

/**

* 功能:从List中随机取出一个元素。
* @author 宋立君

* @date 2014年06月25日
* @param objs 源List

* @return T List的一个元素
*/

publicstatic
<T>T
randomOne(List<T>list){
if(isEmpty(list)){

returnnull;
}

returnlist.get(MathUtil.randomNumber(0,list.size()));
}

/**

* 功能:从数组中随机取出一个元素。
* @author 宋立君

* @date 2014年06月25日
* @param objs 源数组

* @return T 数组的一个元素
*/

publicstatic
<T>T
randomOne(T[]objs){
if(isEmpty(objs)){

returnnull;
}

returnobjs[MathUtil.randomNumber(0,objs.length)];
}

/**

* 功能:数组中是否存在这个元素。
* @author 宋立君

* @date 2014年06月25日
* @param objArr 数组

* @param compare 元素
* @return 存在返回true,否则返回false。

*/
publicstatic
<T>boolean
arrayContain(T[]objArr,Tcompare){

if(isEmpty(objArr)){
returnfalse;

}
for(Tobj
:objArr){

if(obj.equals(compare)){
returntrue;

}
}

returnfalse;
}

/**
* 功能:向list中添加数组。

* @author 宋立君
* @date 2014年06月25日

* @param list List
* @param array 数组

*/
publicstatic
<T>void
addArrayToList(List<T>list,T[]array){

if(isEmpty(list)){
return;

}
for(Tt
:array){

list.add(t);
}

}

/**
* 功能:将数组进行反转,倒置。

* @author 宋立君
* @date 2014年06月25日

* @param objs 源数组
* @return T[] 反转后的数组

*/
publicstatic
<T>T[]reverseArray(T[]objs){

if(isEmpty(objs)){
returnnull;

}
T[]res=(T[])java.lang.reflect.Array.newInstance(objs[0].getClass(),objs.length);

//新序号
intk=0;

for(inti=objs.length-1;
i>=0;
i--){
res[k++]=objs[i];

}
returnres;

}

/**
* 功能:将数组转为list。

* @author 宋立君
* @date 2014年06月25日

* @param objs 源数组
* @return List

*/
publicstatic
<T>List<T>arrayToList(T[]objs){

if(isEmpty(objs)){
returnnull;

}
List<T>list=newLinkedList<T>();

for(Tobj
:objs){
list.add(obj);

}
returnlist;

}

/**
* 功能:将list转为数组。

* @author 宋立君
* @date 2014年06月25日

* @param list 源list
* @return T[]

*/
publicstatic
<T>T[]listToArray(List<T>list){

if(isEmpty(list)){
returnnull;

}
T[]objs=(T[])java.lang.reflect.Array.newInstance(list.get(0).getClass(),list.size());

inti=0;//数组下标。
for(Tobj
:list){

objs[i++]=obj;
}

returnobjs;
}

/**

* 将一个字符串数组的内容全部添加到另外一个数组中,并返回一个新数组。
* @param array1 第一个数组

* @param array2 第二个数组
* @return T[] 拼接后的新数组

*/
publicstatic
<T>T[]concatenateArrays(T[]array1,T[]array2){

if(isEmpty(array1)){
returnarray2;

}
if(isEmpty(array2)){

returnarray1;
}

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);
returnresArray;

}

/**
* 将一个object添加到一个数组中,并返回一个新数组。

* @param array被添加到的数组
* @param object 被添加的object

* @return T[] 返回的新数组
*/

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

returnresArray;
}

//原数组不为空时。
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;

returnresArray;
}

/**

* 功能:判断数组是不是空。(null或者length==0)
* @author 宋立君

* @date 2014年06月25日
* @param array 数组

* @return boolean 空返回true,否则返回false。
*/

publicstatic
<T>boolean
isEmpty(T[]array){
return(array==
null||
array.length==0);

}

/**

* 功能:集合是否为空。如果传入的值为null或者集合不包含元素都认为为空。
* @author 宋立君

* @date 2014年06月25日
* @param collection 集合

* @return boolean 为空返回true,否则返回false。
*/

publicstatic
booleanisEmpty(Collectioncollection){
return(collection==
null||
collection.isEmpty());

}

/**
* 功能:Map是否为空。如果传入的值为null或者集合不包含元素都认为为空。

* @author 宋立君
* @date 2014年06月25日

* @param map Map
* @return boolean 为空返回true,否则返回false。

*/
publicstatic
booleanisEmpty(Mapmap){

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

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

packagecom.itjh.javaUtil;

importjava.math.BigDecimal;

/**

* 数学运算辅助类。
*

* @author 宋立君
* @date 2014年06月25日

*/
publicclass
MathUtil{

/**

* 功能:将字符串转换为BigDecimal,一般用于数字运算时。
*

* @author 宋立君
* @date 2014年06月25日

* @param str
* 字符串

* @return BigDecimal,str为empty时返回null。
*/

publicstatic
BigDecimaltoBigDecimal(Stringstr){
if(StringUtil.isEmpty(str)){

returnnull;
}

returnnew
BigDecimal(str);
}

/**

* 功能:将字符串抓换为double,如果失败返回默认值。
*

* @author 宋立君
* @date 2014年06月25日

* @param str
* 字符串

* @param defaultValue
* 失败时返回的默认值

* @return double
*/

publicstatic
doubletoDouble(Stringstr,double
defaultValue){
if(str==
null){

returndefaultValue;
}

try{
returnDouble.parseDouble(str);

}catch
(NumberFormatExceptionnfe){
returndefaultValue;

}
}

/**

* 功能:将字符串抓换为float,如果失败返回默认值。
*

* @author 宋立君
* @date 2014年06月25日

* @param str
* 字符串

* @param defaultValue
* 失败时返回的默认值

* @return float
*/

publicstatic
floattoFloat(Stringstr,float
defaultValue){
if(str==
null){

returndefaultValue;
}

try{
returnFloat.parseFloat(str);

}catch
(NumberFormatExceptionnfe){
returndefaultValue;

}
}

/**

* 功能:将字符串抓换为long,如果失败返回默认值。
*

* @author 宋立君
* @date 2014年06月25日

* @param str
* 字符串

* @param defaultValue
* 失败时返回的默认值

* @return long
*/

publicstatic
longtoLong(Stringstr,long
defaultValue){
if(str==
null){

returndefaultValue;
}

try{
returnLong.parseLong(str);

}catch
(NumberFormatExceptionnfe){
returndefaultValue;

}
}

/**

* 功能:将字符串抓换为int,如果失败返回默认值。
*

* @author 宋立君
* @date 2014年06月25日

* @param str
* 字符串

* @param defaultValue
* 失败时返回的默认值

* @return int
*/

publicstatic
inttoInt(Stringstr,int
defaultValue){
if(str==
null){

returndefaultValue;
}

try{
returnInteger.parseInt(str);

}catch
(NumberFormatExceptionnfe){
returndefaultValue;

}
}

/**

* <p>
* 得到两个 <code>double</code>值中最大的一个.

* </p>
*

* @param a
* 值 1

* @param b
* 值 2

* @return 最大的值
* @author 宋立君

* @date 2014年06月25日
*/

publicstatic
floatgetMax(floata,float
b){
if(Float.isNaN(a)){

returnb;
}else
if(Float.isNaN(b)){

returna;
}else
{

returnMath.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日

*/
publicstatic
floatgetMax(float[]array){

// Validates input
if(array==
null){

thrownew
IllegalArgumentException("The Array must not be null");
}else
if(array.length==
0){

thrownew
IllegalArgumentException("Array cannot be empty.");
}

// Finds and returns max

floatmax
=array[0];
for(intj
=1;j
<array.length;j++){

max=
getMax(array[j],max);
}

returnmax;

}

/**
* <p>

* 得到数组中最大的一个.
* </p>

*
* @param array

* 数组不能为null,也不能为空。
* @return 得到数组中最大的一个.

* @throws IllegalArgumentException
* 如果 <code>数组</code> 是 <code>null</code>

* @throws IllegalArgumentException
* 如果 <code>数组</code>是空

* @author 宋立君
* @date 2014年06月25日

*/
publicstatic
doublegetMax(double[]array){

// Validates input
if(array==
null){

thrownew
IllegalArgumentException("The Array must not be null");
}else
if(array.length==
0){

thrownew
IllegalArgumentException("Array cannot be empty.");
}

// Finds and returns max

doublemax
=array[0];
for(intj
=1;j
<array.length;j++){

max=
getMax(array[j],max);
}

returnmax;

}

/**
* <p>

* 得到两个 <code>double</code>值中最大的一个.
* </p>

*
* @param a

* 值 1
* @param b

* 值 2
* @return 最大的值

* @author 宋立君
* @date 2014年06月25日

* */
publicstatic
doublegetMax(doublea,double
b){

if(Double.isNaN(a)){
returnb;

}else
if(Double.isNaN(b)){
returna;

}else
{
returnMath.max(a,b);

}
}

/**

* <p>
* 得到两个float中最小的一个。

* </p>
*

* @param a
* 值 1

* @param b
* 值 2

* @return double值最小的
* @author 宋立君

* @date 2014年06月25日
*/

publicstatic
floatgetMin(floata,float
b){
if(Float.isNaN(a)){

returnb;
}else
if(Float.isNaN(b)){

returna;
}else
{

returnMath.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日

*/
publicstatic
floatgetMin(float[]array){

// Validates input
if(array==
null){

thrownew
IllegalArgumentException("数组不能为null。");
}else
if(array.length==
0){

thrownew
IllegalArgumentException("数组不能为空。");
}

// Finds and returns min

floatmin
=array[0];
for(inti
=1;i
<array.length;i++){

min=
getMin(array[i],min);
}

returnmin;

}

/**
* <p>

* 返回数组中最小的double。
* </p>

*
* @param array

* 数组不能为null,也不能为空。
* @return 数组里面最小的double

* @throws IllegalArgumentException
* 如果<code>数组</code>是<code>null</code>

* @throws IllegalArgumentException
* 如果<code>数组</code>是空

* @author 宋立君
* @date 2014年06月25日

*/
publicstatic
doublegetMin(double[]array){

// Validates input
if(array==
null){

thrownew
IllegalArgumentException("数组不能为null。");
}else
if(array.length==
0){

thrownew
IllegalArgumentException("数组不能为空。");
}

// Finds and returns min
doublemin
=array[0];

for(inti
=1;i
<array.length;i++){
min=
getMin(array[i],min);

}
returnmin;

}

/**
* <p>

* 得到两个double中最小的一个。
* </p>

*
* @param a

* 值 1
* @param b

* 值 2
* @return double值最小的

* @author 宋立君
* @date 2014年06月25日

*/
publicstatic
doublegetMin(doublea,double
b){

if(Double.isNaN(a)){
returnb;

}else
if(Double.isNaN(b)){
returna;

}else
{
returnMath.min(a,b);

}
}

/**

* 返回两个double的商 first除以second。
*

* @param first
* 第一个double

* @param second
* 第二个double

* @return double
* @author 宋立君

* @date 2014年06月25日
*/

publicstatic
doubledivideDouble(doublefirst,double
second){
BigDecimalb1
=new
BigDecimal(first);

BigDecimal b2=
newBigDecimal(second);
returnb1.divide(b2).doubleValue();

}

/**
* 返回两个double的乘积 first*second。

*
* @param first

* 第一个double
* @param second

* 第二个double
* @return double

* @author 宋立君
* @date 2014年06月25日

*/
publicstatic
doublemultiplyDouble(doublefirst,double
second){

BigDecimal b1=
newBigDecimal(first);
BigDecimalb2
=new
BigDecimal(second);

returnb1.multiply(b2).doubleValue();
}

/**

* 返回两个double的差值 first-second。
*

* @param first
* 第一个double

* @param second
* 第二个double

* @return double
* @author 宋立君

* @date 2014年06月25日
*/

publicstatic
doublesubtractDouble(doublefirst,double
second){
BigDecimalb1
=new
BigDecimal(first);

BigDecimal b2=
newBigDecimal(second);
returnb1.subtract(b2).doubleValue();

}

/**
* 返回两个double的和值 first+second。

*
* @param first

* 第一个double
* @param second

* 第二个double
* @return double

* @author 宋立君
* @date 2014年06月25日

*/
publicstatic
doublesumDouble(doublefirst,double
second){

BigDecimal b1=
newBigDecimal(first);
BigDecimalb2
=new
BigDecimal(second);

returnb1.add(b2).doubleValue();
}

/**

* 格式化double指定位数小数。例如将11.123格式化为11.1。
*

* @param value
* 原double数字。

* @param decimals
* 小数位数。

* @return 格式化后的double,注意为硬格式化不存在四舍五入。
* @author 宋立君

* @date 2014年06月25日
*/

publicstatic
StringformatDouble(doublevalue,int
decimals){
StringdoubleStr
=""
+value;

intindex
=doubleStr.indexOf(".")!=
-1?
doubleStr.indexOf(".")
:doubleStr.indexOf(",");

// Decimal point can not be found...
if(index==
-1)

returndoubleStr;
// Truncate all decimals

if(decimals==
0){
returndoubleStr.substring(0,index);

}
intlen
=index
+decimals
+1;

if(len>=
doubleStr.length())
len=
doubleStr.length();

doubled
=Double.parseDouble(doubleStr.substring(0,len));
returnString.valueOf(d);

}

/**
* 生成一个指定位数的随机数,并将其转换为字符串作为函数的返回值。

*
* @param numberLength

* 随机数的位数。
* @return String 注意随机数可能以0开头。

* @author 宋立君
* @date 2014年06月25日

*/
publicstatic
StringrandomNumber(intnumberLength){

// 记录生成的每一位随机数
StringBuffersb
=new
StringBuffer();

for(inti
=0;i
<numberLength;i++){
// 每次生成一位,随机生成一个0-10之间的随机数,不含10。

DoubleranDouble
=Math.floor(Math.random()*
10);
sb.append(ranDouble.intValue());

}
returnsb.toString();

}

/**
* 功能:生成一个在最大数和最小数之间的随机数。会出现最小数,但不会出现最大数。

*
* @author 宋立君

* @date 2014年06月25日
* @param minNum

* 最小数
* @param maxNum

* 最大数
* @return int

*/
publicstatic
intrandomNumber(intminNum,int
maxNum){

if(maxNum<=
minNum){
thrownew
RuntimeException("maxNum必须大于minNum!");

}
// 计算出来差值

intsubtract
=maxNum
-minNum;
DoubleranDouble
=Math.floor(Math.random()*
subtract);

returnranDouble.intValue()+
minNum;
}

/**

* 功能:生成一个在最大数和最小数之间的随机数。会出现最小数,但不会出现最大数。<br/>
* 但不随机notin数组中指定的数字, 如果可随机的范围较小,可能会一直随机不到,或者随机的很慢。

*
* @author 宋立君

* @date 2014年06月25日
* @param minNum

* 最小数
* @param maxNum

* 最大数
* @param notin

* 不随机数组这些数字
* @return int

*/
publicstatic
intrandomNumber(intminNum,int
maxNum,Integer[]notin){

if(notin.length>=
(maxNum-
minNum)){
thrownew
RuntimeException("notin数组的元素已经把可以随机的都排除了,无法得到随机数!");

}
while(true){

intnum
=randomNumber(minNum,maxNum);
if(!CollectionUtil.arrayContain(notin,num)){

returnnum;
}

}
}

}

如果有问题,及时反馈!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: