CommonUtil.java 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. package org.springblade.common.utils;
  2. import cn.hutool.core.io.FileUtil;
  3. import org.apache.commons.lang.StringUtils;
  4. import org.springframework.util.CollectionUtils;
  5. import java.io.*;
  6. import java.math.BigDecimal;
  7. import java.net.HttpURLConnection;
  8. import java.net.URL;
  9. import java.net.URLConnection;
  10. import java.util.*;
  11. import java.util.regex.Matcher;
  12. import java.util.regex.Pattern;
  13. import java.util.stream.Collectors;
  14. import java.util.stream.Stream;
  15. import java.util.zip.ZipEntry;
  16. import java.util.zip.ZipOutputStream;
  17. /**
  18. * 通用工具类
  19. *
  20. * @author Chill
  21. */
  22. public class CommonUtil {
  23. public static Boolean checkBigDecimal(Object value){
  24. try{
  25. if(value != null && StringUtils.isNotEmpty(value.toString())){
  26. new BigDecimal(value.toString());
  27. return true;
  28. }
  29. }catch (Exception e){
  30. e.printStackTrace();
  31. }
  32. return false;
  33. }
  34. public static void removeFile(List<String> removeList){
  35. for(String fileUrl : removeList){
  36. try{
  37. FileUtil.del(new File(fileUrl));
  38. }catch (Exception e){
  39. e.printStackTrace();
  40. }
  41. }
  42. }
  43. public static String handleNull(Object obj) {
  44. if (null == obj) {
  45. return "";
  46. } else {
  47. return obj.toString().trim();
  48. }
  49. }
  50. public static String join(Object ...args){
  51. if(args!=null){
  52. if(args.length>2){
  53. List<String> list = Arrays.stream(args).limit(args.length - 1).map(CommonUtil::handleNull).collect(Collectors.toList());
  54. String split=handleNull(args[args.length-1]);
  55. return join(list, split);
  56. }else{
  57. return handleNull(args[0]);
  58. }
  59. }else {
  60. return "";
  61. }
  62. }
  63. public static String join(List<String>list, String split){
  64. StringBuilder sb = new StringBuilder();
  65. if(list != null && list.size() > 0){
  66. for(String str:list){
  67. if(StringUtils.isNotEmpty(str)){
  68. sb.append(str).append(split);
  69. }
  70. }
  71. if(sb.length()>0 && StringUtils.isNotEmpty(split)){
  72. sb.delete(sb.length() - split.length(), sb.length());
  73. }
  74. }
  75. return sb.toString();
  76. }
  77. public static Matcher matcher(String regex, String value) {
  78. Pattern pattern = Pattern.compile(regex);
  79. return pattern.matcher(value);
  80. }
  81. /**
  82. * 根据OSS文件路径获取文件输入流
  83. */
  84. public static InputStream getOSSInputStream(String urlStr) throws Exception {
  85. //获取OSS文件流
  86. URL imageUrl = new URL(urlStr);
  87. try {
  88. HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
  89. conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
  90. return conn.getInputStream();
  91. }catch (Exception e){
  92. return null;
  93. }
  94. }
  95. /**
  96. * 获取字节数组
  97. */
  98. public static byte[] InputStreamToBytes(InputStream is) throws IOException {
  99. BufferedInputStream bis = new BufferedInputStream(is);
  100. ByteArrayOutputStream os = new ByteArrayOutputStream();
  101. int date = -1;
  102. while ((date = bis.read()) != -1) {
  103. os.write(date);
  104. }
  105. return os.toByteArray();
  106. }
  107. /**
  108. * 随机生成短信验证码
  109. * @param length 生成长度
  110. */
  111. public static String getCharAndNumber(int length) {
  112. StringBuilder val = new StringBuilder();
  113. Random random = new Random();
  114. for (int i = 0; i < length; i++) {
  115. String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num";
  116. if ("char".equalsIgnoreCase(charOrNum)) {
  117. int choice = random.nextInt(2) % 2 == 0 ? 65 : 97;
  118. val.append((char) (choice + random.nextInt(26)));
  119. } else {
  120. val.append(random.nextInt(10));
  121. }
  122. }
  123. return val.toString();
  124. }
  125. /**
  126. * 判断参数是否是数字
  127. * @param value 需要判断数据
  128. * @return 判断结果,数字则为true,反之false
  129. */
  130. public static boolean checkIsBigDecimal(Object value){
  131. try{
  132. if(value != null && StringUtils.isNotEmpty(String.valueOf(value))){
  133. new BigDecimal(String.valueOf(value));
  134. return true;
  135. } else {
  136. return false;
  137. }
  138. }catch (Exception e){
  139. return false;
  140. }
  141. }
  142. /**
  143. * 根据每页信息分组
  144. */
  145. public static <T> List<List<T>> getBatchSize(List<T> allIds, int size) {
  146. List<List<T>> batchIds = new ArrayList<>();
  147. if (allIds == null || allIds.size() == 0 || size <= 0) {
  148. return batchIds;
  149. }
  150. int i = 0;
  151. List<T> tmp = new ArrayList<>();
  152. for (T map : allIds) {
  153. tmp.add(map);
  154. i++;
  155. if (i % size == 0 || i == allIds.size()) {
  156. batchIds.add(tmp);
  157. tmp = new ArrayList<>();
  158. }
  159. }
  160. return batchIds;
  161. }
  162. /**
  163. * @param src
  164. * @throws IOException
  165. * @throws ClassNotFoundException
  166. */
  167. public static <T> List<T> deepCopy(List<T> src) throws IOException, ClassNotFoundException {
  168. ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
  169. ObjectOutputStream out = new ObjectOutputStream(byteOut);
  170. out.writeObject(src);
  171. ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray());
  172. ObjectInputStream in = new ObjectInputStream(byteIn);
  173. @SuppressWarnings("unchecked")
  174. List<T> dest = (List<T>) in.readObject();
  175. return dest;
  176. }
  177. /**
  178. * Description: Java8 Stream分割list集合
  179. * @param list 集合数据
  180. * @param splitSize 几个分割一组
  181. * @return 集合分割后的集合
  182. */
  183. public static <T> List<List<T>> splitList(List<T> list, int splitSize) {
  184. //判断集合是否为空
  185. if (CollectionUtils.isEmpty(list))
  186. return Collections.emptyList();
  187. //计算分割后的大小
  188. int maxSize = (list.size() + splitSize - 1) / splitSize;
  189. //开始分割
  190. return Stream.iterate(0, n -> n + 1)
  191. .limit(maxSize)
  192. .parallel()
  193. .map(a -> list.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList()))
  194. .filter(b -> !b.isEmpty())
  195. .collect(Collectors.toList());
  196. }
  197. /**
  198. * 流写入文件
  199. *
  200. * @param inputStream 文件输入流
  201. * @param file 输出文件
  202. */
  203. public static void inputStreamToFile(InputStream inputStream, File file) {
  204. try {
  205. OutputStream os = new FileOutputStream(file);
  206. int bytesRead = 0;
  207. byte[] buffer = new byte[8192];
  208. while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
  209. os.write(buffer, 0, bytesRead);
  210. }
  211. os.close();
  212. inputStream.close();
  213. } catch (Exception e) {
  214. e.printStackTrace();
  215. }
  216. }
  217. /**
  218. * 删除文件夹下所有文件
  219. * @param path
  220. * @return
  221. */
  222. public static boolean deleteDir(String path) {
  223. File file = new File(path);
  224. if (!file.exists()) {//判断是否待删除目录是否存在
  225. System.err.println("The dir are not exists!");
  226. return false;
  227. }
  228. String[] content = file.list();//取得当前目录下所有文件和文件夹
  229. for (String name : content) {
  230. File temp = new File(path, name);
  231. if (temp.isDirectory()) {//判断是否是目录
  232. deleteDir(temp.getAbsolutePath());//递归调用,删除目录里的内容
  233. temp.delete();//删除空目录
  234. } else {
  235. if (!temp.delete()) {//直接删除文件
  236. System.err.println("Failed to delete " + name);
  237. }
  238. }
  239. }
  240. return true;
  241. }
  242. /**
  243. * 压缩指定路径下的文件夹
  244. * @param filesPath
  245. * @throws Exception
  246. */
  247. public static void packageZip(String filesPath) throws Exception {
  248. // 要被压缩的文件夹
  249. File file = new File(filesPath); //需要压缩的文件夹
  250. File zipFile = new File(filesPath + ".zip"); //放于和需要压缩的文件夹同级目录
  251. ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile));
  252. isDirectory(file, zipOut, "", true); //判断是否为文件夹
  253. zipOut.close();
  254. }
  255. public static void isDirectory(File file, ZipOutputStream zipOutputStream, String filePath, boolean flag) throws IOException {
  256. //判断是否为问加减
  257. if (file.isDirectory()) {
  258. File[] files = file.listFiles(); //获取该文件夹下所有文件(包含文件夹)
  259. filePath = flag == true ? file.getName() : filePath + File.separator + file.getName(); //首次为选中的文件夹,即根目录,之后递归实现拼接目录
  260. for (int i = 0; i < files.length; ++i) {
  261. //判断子文件是否为文件夹
  262. if (files[i].isDirectory()) {
  263. //进入递归,flag置false 即当前文件夹下仍包含文件夹
  264. isDirectory(files[i], zipOutputStream, filePath, false);
  265. } else {
  266. //不为文件夹则进行压缩
  267. InputStream input = new FileInputStream(files[i]);
  268. zipOutputStream.putNextEntry(new ZipEntry(filePath + File.separator + files[i].getName()));
  269. int temp = 0;
  270. while ((temp = input.read()) != -1) {
  271. zipOutputStream.write(temp);
  272. }
  273. input.close();
  274. }
  275. }
  276. } else {
  277. //将子文件夹下的文件进行压缩
  278. InputStream input = new FileInputStream(file);
  279. zipOutputStream.putNextEntry(new ZipEntry(file.getPath()));
  280. int temp = 0;
  281. while ((temp = input.read()) != -1) {
  282. zipOutputStream.write(temp);
  283. }
  284. input.close();
  285. }
  286. }
  287. /**
  288. * @param urlStr
  289. * @return 返回Url资源大小
  290. * @throws IOException
  291. */
  292. public static long getResourceLength(String urlStr) throws IOException {
  293. URL url = new URL(urlStr);
  294. URLConnection urlConnection = url.openConnection();
  295. urlConnection.connect();
  296. //返回响应报文头字段Content-Length的值
  297. return urlConnection.getContentLength();
  298. }
  299. }