package org.springblade.common.utils; import cn.hutool.core.io.FileUtil; import org.apache.commons.lang.StringUtils; import org.springframework.util.CollectionUtils; import java.io.*; import java.math.BigDecimal; import java.net.HttpURLConnection; import java.net.URL; import java.net.URLConnection; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; import java.util.stream.Stream; import java.util.zip.ZipEntry; import java.util.zip.ZipOutputStream; /** * 通用工具类 * * @author Chill */ public class CommonUtil { public static Boolean checkBigDecimal(Object value){ try{ if(value != null && StringUtils.isNotEmpty(value.toString())){ new BigDecimal(value.toString()); return true; } }catch (Exception e){ e.printStackTrace(); } return false; } public static void removeFile(List removeList){ for(String fileUrl : removeList){ try{ FileUtil.del(new File(fileUrl)); }catch (Exception e){ e.printStackTrace(); } } } public static String handleNull(Object obj) { if (null == obj) { return ""; } else { return obj.toString().trim(); } } public static String join(Object ...args){ if(args!=null){ if(args.length>2){ List list = Arrays.stream(args).limit(args.length - 1).map(CommonUtil::handleNull).collect(Collectors.toList()); String split=handleNull(args[args.length-1]); return join(list, split); }else{ return handleNull(args[0]); } }else { return ""; } } public static String join(Listlist, String split){ StringBuilder sb = new StringBuilder(); if(list != null && list.size() > 0){ for(String str:list){ if(StringUtils.isNotEmpty(str)){ sb.append(str).append(split); } } if(sb.length()>0 && StringUtils.isNotEmpty(split)){ sb.delete(sb.length() - split.length(), sb.length()); } } return sb.toString(); } public static Matcher matcher(String regex, String value) { Pattern pattern = Pattern.compile(regex); return pattern.matcher(value); } /** * 根据OSS文件路径获取文件输入流 */ public static InputStream getOSSInputStream(String urlStr) throws Exception { //获取OSS文件流 URL imageUrl = new URL(urlStr); try { HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection(); conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)"); return conn.getInputStream(); }catch (Exception e){ return null; } } /** * 获取字节数组 */ public static byte[] InputStreamToBytes(InputStream is) throws IOException { BufferedInputStream bis = new BufferedInputStream(is); ByteArrayOutputStream os = new ByteArrayOutputStream(); int date = -1; while ((date = bis.read()) != -1) { os.write(date); } return os.toByteArray(); } /** * 随机生成短信验证码 * @param length 生成长度 */ public static String getCharAndNumber(int length) { StringBuilder val = new StringBuilder(); Random random = new Random(); for (int i = 0; i < length; i++) { String charOrNum = random.nextInt(2) % 2 == 0 ? "char" : "num"; if ("char".equalsIgnoreCase(charOrNum)) { int choice = random.nextInt(2) % 2 == 0 ? 65 : 97; val.append((char) (choice + random.nextInt(26))); } else { val.append(random.nextInt(10)); } } return val.toString(); } /** * 判断参数是否是数字 * @param value 需要判断数据 * @return 判断结果,数字则为true,反之false */ public static boolean checkIsBigDecimal(Object value){ try{ if(value != null && StringUtils.isNotEmpty(String.valueOf(value))){ new BigDecimal(String.valueOf(value)); return true; } else { return false; } }catch (Exception e){ return false; } } /** * 根据每页信息分组 */ public static List> getBatchSize(List allIds, int size) { List> batchIds = new ArrayList<>(); if (allIds == null || allIds.size() == 0 || size <= 0) { return batchIds; } int i = 0; List tmp = new ArrayList<>(); for (T map : allIds) { tmp.add(map); i++; if (i % size == 0 || i == allIds.size()) { batchIds.add(tmp); tmp = new ArrayList<>(); } } return batchIds; } /** * @param src * @throws IOException * @throws ClassNotFoundException */ public static List deepCopy(List src) throws IOException, ClassNotFoundException { ByteArrayOutputStream byteOut = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(byteOut); out.writeObject(src); ByteArrayInputStream byteIn = new ByteArrayInputStream(byteOut.toByteArray()); ObjectInputStream in = new ObjectInputStream(byteIn); @SuppressWarnings("unchecked") List dest = (List) in.readObject(); return dest; } /** * Description: Java8 Stream分割list集合 * @param list 集合数据 * @param splitSize 几个分割一组 * @return 集合分割后的集合 */ public static List> splitList(List list, int splitSize) { //判断集合是否为空 if (CollectionUtils.isEmpty(list)) return Collections.emptyList(); //计算分割后的大小 int maxSize = (list.size() + splitSize - 1) / splitSize; //开始分割 return Stream.iterate(0, n -> n + 1) .limit(maxSize) .parallel() .map(a -> list.parallelStream().skip(a * splitSize).limit(splitSize).collect(Collectors.toList())) .filter(b -> !b.isEmpty()) .collect(Collectors.toList()); } /** * 流写入文件 * * @param inputStream 文件输入流 * @param file 输出文件 */ public static void inputStreamToFile(InputStream inputStream, File file) { try { OutputStream os = new FileOutputStream(file); int bytesRead = 0; byte[] buffer = new byte[8192]; while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) { os.write(buffer, 0, bytesRead); } os.close(); inputStream.close(); } catch (Exception e) { e.printStackTrace(); } } /** * 删除文件夹下所有文件 * @param path * @return */ public static boolean deleteDir(String path) { File file = new File(path); if (!file.exists()) {//判断是否待删除目录是否存在 System.err.println("The dir are not exists!"); return false; } String[] content = file.list();//取得当前目录下所有文件和文件夹 for (String name : content) { File temp = new File(path, name); if (temp.isDirectory()) {//判断是否是目录 deleteDir(temp.getAbsolutePath());//递归调用,删除目录里的内容 temp.delete();//删除空目录 } else { if (!temp.delete()) {//直接删除文件 System.err.println("Failed to delete " + name); } } } return true; } /** * 压缩指定路径下的文件夹 * @param filesPath * @throws Exception */ public static void packageZip(String filesPath) throws Exception { // 要被压缩的文件夹 File file = new File(filesPath); //需要压缩的文件夹 File zipFile = new File(filesPath + ".zip"); //放于和需要压缩的文件夹同级目录 ZipOutputStream zipOut = new ZipOutputStream(new FileOutputStream(zipFile)); isDirectory(file, zipOut, "", true); //判断是否为文件夹 zipOut.close(); } public static void isDirectory(File file, ZipOutputStream zipOutputStream, String filePath, boolean flag) throws IOException { //判断是否为问加减 if (file.isDirectory()) { File[] files = file.listFiles(); //获取该文件夹下所有文件(包含文件夹) filePath = flag == true ? file.getName() : filePath + File.separator + file.getName(); //首次为选中的文件夹,即根目录,之后递归实现拼接目录 for (int i = 0; i < files.length; ++i) { //判断子文件是否为文件夹 if (files[i].isDirectory()) { //进入递归,flag置false 即当前文件夹下仍包含文件夹 isDirectory(files[i], zipOutputStream, filePath, false); } else { //不为文件夹则进行压缩 InputStream input = new FileInputStream(files[i]); zipOutputStream.putNextEntry(new ZipEntry(filePath + File.separator + files[i].getName())); int temp = 0; while ((temp = input.read()) != -1) { zipOutputStream.write(temp); } input.close(); } } } else { //将子文件夹下的文件进行压缩 InputStream input = new FileInputStream(file); zipOutputStream.putNextEntry(new ZipEntry(file.getPath())); int temp = 0; while ((temp = input.read()) != -1) { zipOutputStream.write(temp); } input.close(); } } /** * @param urlStr * @return 返回Url资源大小 * @throws IOException */ public static long getResourceLength(String urlStr) throws IOException { URL url = new URL(urlStr); URLConnection urlConnection = url.openConnection(); urlConnection.connect(); //返回响应报文头字段Content-Length的值 return urlConnection.getContentLength(); } }