首页 技术 正文
技术 2022年11月21日
0 收藏 539 点赞 4,498 浏览 22887 个字

1、FtpUtil

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

2、 汉字转拼音

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

3、zip工具类

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

4 CollectionUtil代码:

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

5 MathUtil代码:

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