Java常用工具方法

常用工具类方法

    /**
     * 时间格式化方法
     */
    private static void dateTimeFormat(){
        // SimpleDateFormat simpleDateFormat = new SimpleDateFormat();
        DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        String format = dateTimeFormatter.format(LocalDateTime.now());
        System.out.println(format);
    }
    
    /**
     * base64 编码
     * @param data
     * @return
     */
    private static String t4(String data){
        return new String(Base64.getEncoder().encode(data.getBytes()), StandardCharsets.UTF_8);
    }

    /**
     * base64 解码
     * @param data
     * @return
     */
    private static String t5(String data) {
        return new String(Base64.getDecoder().decode(data),StandardCharsets.UTF_8);
    }
    
    /**
     * 对象转map
     */
    import org.springframework.cglib.beans.BeanMap;
    
    public static <T> Map<String, Object> beanToMap(T bean) {
        Map<String, Object> map = new HashMap<>();
        if (bean != null) {
            BeanMap beanMap = BeanMap.create(bean);
            for (Object key : beanMap.keySet()) {
                if(beanMap.get(key) != null)
                    map.put(key + "", beanMap.get(key));
            }
        }
        return map;
    }

对象排序,空在前

    /**
     * java8对象排序 空在前
     */
    private static void t6(){

        class User {
            private Integer age;

            private String name;

            public User(String name) {
                this.name = name;
            }

            public User(Integer age, String name) {
                this.age = age;
                this.name = name;
            }

            public User() {
            }

            public Integer getAge() {
                return age;
            }

            public void setAge(Integer age) {
                this.age = age;
            }

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            @Override
            public String toString() {
                return "User{" +
                        "age=" + age +
                        ", name='" + name + '\'' +
                        '}';
            }
        }

        List<User> originList = new ArrayList<>();
        originList.add(new User(18,"aa"));
        originList.add(new User(20,"bb"));
        originList.add(new User(17,"cc"));
        originList.add(new User(5,"dd"));
        originList.add(new User(9,"ee"));
        originList.add(new User(13,"ff"));
        originList.add(new User("gg"));
        originList.add(new User("hh"));

        List<User> collect = originList.stream()
                .sorted(Comparator.comparing(User::getAge, Comparator.nullsFirst(Integer::compareTo)))
                .collect(Collectors.toList());
        collect.stream().forEach(System.out::println);
    }


线程池

  • 例一 创建java线程池
@Configuration
public class CustomThreadPool {

    private int corePoolSize = 3;

    private int maxPoolSize = 8;

    private int keepAliveTime = 20;

    private int queueCapacity = 2048;

    @Bean(name = "one")
    public ThreadPoolExecutor threadPoolExecutor() {
        // 获取CPU核数,动态创建线程池
        // int sectionThread = Runtime.getRuntime().availableProcessors();
        return new ThreadPoolExecutor(corePoolSize, maxPoolSize,
                keepAliveTime, TimeUnit.SECONDS, new LinkedBlockingQueue<>(queueCapacity), new CustomThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }

    class CustomThreadFactory implements ThreadFactory {
        AtomicInteger atomicInteger = new AtomicInteger(1);

        @Override
        public Thread newThread(Runnable r) {
            Thread thread = new Thread(r);
            thread.setName("one-" + atomicInteger.getAndIncrement());
            return thread;
        }
    }

}
  • 例二 创建spring线程池
@Configuration
public class TaskExecutePool {

    @Resource
    private TaskThreadPoolConfig config;

    /**
     *  操作记录线程池配置
     * @return
     */
    @Bean
    public Executor userOptLogTaskAsyncPool() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(this.config.getCorePoolSize());
        executor.setMaxPoolSize(this.config.getMaxPoolSize());
        executor.setQueueCapacity(this.config.getQueueCapacity());
        executor.setKeepAliveSeconds(this.config.getKeepAliveSeconds());
        executor.setThreadNamePrefix("gateway-opt-log-pool");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }
}

获取网络图片

    /**
     * 获取网络图片url上传至fastdfs
     *
     * @param imageUrl
     * @return
     * @throws IOException
     */
    public String uploadURLImage(String imageUrl) throws IOException {
        URL url = new URL(imageUrl);
        InputStream inputStream = url.openStream();
        FileResult fileResult = imageUploadDFS(fileToMultipart(inputStream, imageUrl.substring(imageUrl.lastIndexOf("/"))));
        if (null == fileResult || !"Success".equalsIgnoreCase(fileResult.getCode())) {
            return "";
        }
        return fileResult.getFilePath();
    }

    private MultipartFile fileToMultipart(InputStream inputStream, String fileName) throws IOException {
        FileItem item = new DiskFileItemFactory().createItem("file"
                , MediaType.MULTIPART_FORM_DATA_VALUE
                , true
                , fileName);
        OutputStream os = item.getOutputStream();
        // 流转移
        IOUtils.copy(inputStream, os);
        return new CommonsMultipartFile(item);
    }

    /**
     * 批量获取网络图片上传至fastdfs
     *
     * @param urls
     * @return
     */
    public Map<Integer, FileResult> uploadImage(List<String > urls) {
        if (CollectionUtils.isEmpty(urls)) {
            return Collections.EMPTY_MAP;
        }
        List<FileUploadInfo> fileUploadInfoList = urls.stream().map(urlStr -> {
            try {
                URL url = new URL(urlStr);
                LocalDateTime now = LocalDateTime.now();
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy/MM/dd");
                String folder = dateTimeFormatter.format(now);
                String uuid = UUID.randomUUID().toString().replace("-", "");
                String extensionName = urlStr.substring(urlStr.lastIndexOf("."));
                String fileName = new StringBuilder().append(folder).append(uuid).append(extensionName).toString();
                log.error("fileName:{}", fileName);
                InputStream inputStream = url.openStream();
                return FileUploadInfo.builder().fileName(fileName).fileIs(inputStream).build();
            } catch (Exception e) {
                log.error("build fileInfo exception, imageUrls:{}", urls);
                return null;
            }
        }).collect(Collectors.toList());

        if (!CollectionUtils.isEmpty(fileUploadInfoList)) {
            fileUploadInfoList = fileUploadInfoList.stream().filter(info -> !Objects.isNull(info))
                    .collect(Collectors.toList());
            return iFileOperateServiceBiz.uploadFile(fileUploadInfoList);
        }else {
            return Collections.EMPTY_MAP;
        }
    }

手机号脱敏& 校验

    /**
     * 明文手机号脱敏
     *
     * @param phoneNum 明文手机号
     * @return
     */
    public static String desensitizePhone(String phoneNum) {
        if (StringUtil.isNotEmpty(phoneNum) && phoneNum.length() == 11) {
            return phoneNum.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        }
        return null;
    }

    private static final Pattern PHONE_PATTERN = Pattern.compile("^1[3|4|5|6|7|8|9][0-9]\\d{8}$");

    /**
     * 校验手机号
     *
     * @param phoneNum
     * @return
     */
    public static Boolean isPhoneNum(String phoneNum) {
        Matcher matcher = PHONE_PATTERN.matcher(phoneNum);
        return matcher.matches();
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值