java工具类(持续更新)

1、lambda表达式对两个List进行循环,根据符合条件,进行相关的赋值操作并返回这个对象集合

/**
     * lambda表达式对两个List进行循环,根据符合条件,进行相关的赋值操作并返回这个对象集合
     *
     * @param sourceList   待设置源列表
     * @param srcEqualProp 源对象条件判断属性名
     * @param srcSetProp   源对象待设置属性名
     * @param targetList   资源提供者列表
     * @param tarEqualProp 对象条件判断参数名
     * @param tarGetProp   待获取对象属性名
     * @param <T>
     * @param <U>
     * @return
     */
    public static <T, U> List<T> setListByEqualObjProperty(List<T> sourceList, String srcEqualProp, String srcSetProp,
                                                           List<U> targetList, String tarEqualProp, String tarGetProp) {
        List<T> resultList = Lists.newArrayList();
        resultList = sourceList.stream()
                .map(sur -> targetList.stream()
                        .filter(tar -> Objects.equals(getValueByPropName(sur, srcEqualProp), getValueByPropName(tar, tarEqualProp)))
                        .findFirst()
                        .map(tar -> {
                            setValueByPropName(sur, srcSetProp, getValueByPropName(tar, tarGetProp));
                            return sur;
                        }).orElse(sur))
                .collect(Collectors.toList());
        return resultList;
    }

    /**
     * @description 通过属性获取传入对象的指定属性的值
     * @author LIXINJIAN 
     * @updateTime 2021/11/12 18:33 
     */
    public static <T> T getValueByPropName(Object object, String propName) {
        T value = null;
        try {
            // 通过属性获取对象的属性
            Field field = object.getClass().getDeclaredField(propName);
            // 对象的属性的访问权限设置为可访问
            field.setAccessible(true);
            // 获取属性的对应的值
            value = (T) field.get(object);
        } catch (Exception e) {
            return null;
        }
        return value;
    }

    // 通过属性设置传入对象的指定属性的值
    public static <U> void setValueByPropName(Object object, String propName, U updateValue) {

        try {
            // 通过属性获取对象的属性
            Field field = object.getClass().getDeclaredField(propName);
            // 对象的属性的访问权限设置为可访问
            field.setAccessible(true);
            // 设置属性的对应的值
            field.set(object, updateValue);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

2、将Object对象里面的属性和值转化成Map对象

/**
     * 将Object对象里面的属性和值转化成Map对象
     *
     * @param obj
     * @return
     * @throws IllegalAccessException
     */
    public static Map<String, Object> objectToMap(Object obj) throws IllegalAccessException {
        Map<String, Object> map = new HashMap<String, Object>();
        Class<?> clazz = obj.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = field.get(obj);
            map.put(fieldName, value);
        }
        return map;
    }
  

3、MD5加密

import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

/**
 * @author 
 * @version 1.0.0
 * @ClassName MD5Utils.java
 * @Description MD5Utils
 * @createTime 2021年01月04日 11:45:00
 */
public class MD5Utils {


    public static String getSign(Map<String, Object> paramMap, String appSecret) {
        List<String> keyList = new ArrayList<>();
        for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
            keyList.add(entry.getKey());
        }
        Collections.sort(keyList);
        StringBuffer sb = new StringBuffer();
        sb.append(appSecret);
        for (int i = 0; i < keyList.size(); i++) {
            String key = keyList.get(i);
            sb.append(key);
            sb.append(paramMap.get(key));
        }
        sb.append(appSecret);

        String paramsStr = sb.toString();
        String sign_md5 = MD5Utils.MD5(paramsStr);
        return  sign_md5;
    }


    /**
     * 计算字符串的 md5 值
     *
     * @param s 输入字符串,不能为空
     * @return
     */
    public static String MD5(String s) {
        char hexDigits[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
        try {
            byte[] btInput = s.getBytes();
            MessageDigest mdInst = MessageDigest.getInstance("MD5");
            mdInst.update(btInput);
            byte[] md = mdInst.digest();
            int j = md.length;
            char str[] = new char[j * 2];
            int k = 0;
            for (int i = 0; i < j; i++) {
                byte byte0 = md[i];
                str[k++] = hexDigits[byte0 >>> 4 & 0xf];
                str[k++] = hexDigits[byte0 & 0xf];
            }
            return new String(str);
        } catch (Exception e) {
            return null;
        }
    }
}

4、基于 httpclient 4.3.1版本的 http工具类

import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.AuthSchemes;
import org.apache.http.client.config.CookieSpecs;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.config.Registry;
import org.apache.http.config.RegistryBuilder;
import org.apache.http.conn.socket.ConnectionSocketFactory;
import org.apache.http.conn.socket.PlainConnectionSocketFactory;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @author 
 * @version 1.0.0
 * @ClassName HttpClient.java
 * @Description 基于 httpclient 4.3.1版本的 http工具类
 * @createTime 2021年01月04日 11:45:00
 */
public class HttpClient {
    private static final CloseableHttpClient httpClient;
    private static final CloseableHttpClient httpsClient;
    public static final String CHARSET = "UTF-8";
    public static final String HTTP = "http";
    public static final String HTTPS = "https";

    static {
        RequestConfig config = RequestConfig.custom().setConnectTimeout(60000).setSocketTimeout(15000).build();
        httpClient = HttpClientBuilder.create().setDefaultRequestConfig(config).build();
        //重写验证方法,取消检测SSL
        X509TrustManager manager = new X509TrustManager() {
            @Override
            public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

            }

            @Override
            public X509Certificate[] getAcceptedIssuers() {
                return new X509Certificate[0];
            }
        };
        SSLConnectionSocketFactory scoketFactory = null;
        try {
            SSLContext context = SSLContext.getInstance("TLS");
            context.init(null, new TrustManager[]{manager}, null);
            scoketFactory = new SSLConnectionSocketFactory(context, NoopHostnameVerifier.INSTANCE);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        RequestConfig httpsConfig = RequestConfig.custom().setCookieSpec(CookieSpecs.STANDARD_STRICT).setExpectContinueEnabled(true).setTargetPreferredAuthSchemes(Arrays.asList(AuthSchemes.NTLM, AuthSchemes.DIGEST)).setProxyPreferredAuthSchemes(Arrays.asList(AuthSchemes.BASIC)).build();
        Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE).register("https", scoketFactory).build();
        PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(socketFactoryRegistry);
        httpsClient = HttpClientBuilder.create().setConnectionManager(connectionManager).setDefaultRequestConfig(httpsConfig).build();
    }

    public static String doGet(String url, Map<String, Object> params, String type) throws Exception {
        if (type == "https") {
            return doHttpGet(url, params, CHARSET, httpsClient);
        }
        return doHttpGet(url, params, CHARSET, httpClient);
    }

    public static String doPost(String url, Map<String, Object> params, String type) throws Exception {
        if (type == "https") {
            return doHttpPost(url, params, httpsClient);
        }
        return doHttpPost(url, params, httpClient);
    }

    /**
     * HTTP/HTTPS Get 获取内容
     *
     * @param url     请求的url地址 ?之前的地址
     * @param params  请求的参数
     * @param charset 编码格式
     * @return 页面内容
     */
    public static String doHttpGet(String url, Map<String, Object> params, String charset, CloseableHttpClient httpClient) throws Exception {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            if (params != null && !params.isEmpty()) {
                List<NameValuePair> pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    if (entry.getValue()!=null){
                        String value = entry.getValue().toString();
                        if (value != null) {
                            pairs.add(new BasicNameValuePair(entry.getKey(), value));
                        }
                    }else {
                        pairs.add(new BasicNameValuePair(entry.getKey(), ""));
                    }
                }
                url += "?" + EntityUtils.toString(new UrlEncodedFormEntity(pairs, charset));
            }
            HttpGet httpGet = new HttpGet(url);
            CloseableHttpResponse response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpGet.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            throw e;
        }
    }

    /**
     * HTTP/HTTPS Post 获取内容
     *
     * @param url     请求的url地址 ?之前的地址
     * @param params  请求的参数
     * @return 页面内容
     */
    public static String doHttpPost(String url, Map<String, Object> params, CloseableHttpClient httpClient) throws Exception {
        if (StringUtils.isBlank(url)) {
            return null;
        }
        try {
            List<NameValuePair> pairs = null;
            if (params != null && !params.isEmpty()) {
                pairs = new ArrayList<NameValuePair>(params.size());
                for (Map.Entry<String, Object> entry : params.entrySet()) {
                    String value = entry.getValue().toString();
                    if (value != null) {
                        pairs.add(new BasicNameValuePair(entry.getKey(), value));
                    }
                }
            }
            HttpPost httpPost = new HttpPost(url);
            if (pairs != null && pairs.size() > 0) {
                httpPost.setEntity(new UrlEncodedFormEntity(pairs, CHARSET));
            }
            CloseableHttpResponse response = httpClient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode != 200) {
                httpPost.abort();
                throw new RuntimeException("HttpClient,error status code :" + statusCode);
            }
            HttpEntity entity = response.getEntity();
            String result = null;
            if (entity != null) {
                result = EntityUtils.toString(entity, "utf-8");
            }
            EntityUtils.consume(entity);
            response.close();
            return result;
        } catch (Exception e) {
            throw e;
        }
    }

    public static CloseableHttpClient getHttpClient(){
        return httpClient;
    }
}

5、基于jfinal 的文件上传工具类

import com.jfinal.core.Controller;
import com.jfinal.upload.UploadFile;
import io.jboot.Jboot;
import io.jboot.web.controller.JbootControllerContext;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 
 * @version 1.0.0
 * @ClassName FileUtils.java
 * @Description 文件上传通用方法     返回List<Map<String,Object>> 如果code为1,则上传失败,回滚之前操作,message提示用户
 * @createTime 2022年01月12日 13:57:00
 */
public class FileUtils {

    public List<Map<String,Object>> upload(List<UploadFile> files) throws Exception {

        Integer userId = 1;
        String path = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
        List<Map<String,Object>> mapList = new ArrayList<>();
        //统计新创建文件
        List<File> fileList = new ArrayList<>();
        for (UploadFile file:files) {
            File source = file.getFile();
            String fileName = file.getFileName();
            String extension = fileName.substring(fileName.lastIndexOf("."));
            String prefix;
            if(".png".equals(extension) || ".jpg".equals(extension) || ".gif".equals(extension)){
                prefix = "img";
                fileName = generateWord() + extension;
            }else{
                prefix = "file";
                fileName = userId + "-" + fileName;
            }
            Map<String,Object> map = new HashMap();
            FileInputStream fis = null;
            FileOutputStream fos = null;
            try {
                fis = new FileInputStream(source);
                File targetDir = new File(Jboot.configValue("top.upload.savepath") + "/" + prefix + "/" + path);
                if (!targetDir.exists()) {
                    targetDir.mkdirs();
                }
                File target = new File(targetDir, fileName);
                //if (!target.exists()) {
                    target.createNewFile();
                    //记录新创建的文件
                    fileList.add(target);
                //}
                fos = new FileOutputStream(target);
                byte[] bts = new byte[300];
                while (fis.read(bts, 0, 300) != -1) {
                    fos.write(bts, 0, 300);
                }
                fos.close();
                fis.close();
                map.put("code", 0);
                map.put("fileName", file.getFileName());
                map.put("extension", extension);
                map.put("file_addr", Jboot.configValue("top.upload.httppath") + "/" + prefix + "/" + path + "/" + fileName);
                mapList.add(map);
            } catch (FileNotFoundException e) {
                fos.close();
                fis.close();
                map.put("code", 1);
                map.put("message", "文件上传出现错误,请稍后再上传:" + file.getFileName());
                mapList = new ArrayList<>();
                mapList.add(map);
                //异常回滚
                deleteFiles(fileList);
                return mapList;
            } catch (IOException e) {
                map.put("code", 1);
                map.put("message", "文件写入服务器出现错误,请稍后再上传:" + file.getFileName());
                mapList = new ArrayList<>();
                mapList.add(map);
                fos.close();
                fis.close();
                //异常回滚
                deleteFiles(fileList);
                return mapList;
            } catch (Exception e){
                fos.close();
                fis.close();
                map.put("code", 1);
                map.put("message", "文件写入服务器出现错误,请稍后再上传:" + file.getFileName());
                mapList = new ArrayList<>();
                mapList.add(map);
                //异常回滚
                deleteFiles(fileList);
                return mapList;
            }finally {
                //删除源文件
                source.delete();
            }
        }
        return mapList;
    }

    private String generateWord() {
        String[] beforeShuffle = new String[] { "2", "3", "4", "5", "6", "7",
                "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J",
                "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
                "W", "X", "Y", "Z" };
        List<String> list = Arrays.asList(beforeShuffle);
        Collections.shuffle(list);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < list.size(); i++) {
            sb.append(list.get(i));
        }
        String afterShuffle = sb.toString();
        String result = afterShuffle.substring(0, 9);
        return result;
    }


   /* public void download(){
        String path = getPara(0);
        String img = PathKit.getWebRootPath() + "/img/u/" + path.replaceAll("_", "/");
        ZipUtil.zip(img, PathKit.getWebRootPath() + "/img/temp/" + path);
        renderFile("/img/temp/" + path + ".zip");
    }*/


    /**
     * @description 批量删除文件
     * @author 
     * @updateTime 2022/1/13 10:10
     */
    public void deleteFiles(List<File> fileList){
        for (File file:fileList){
            file.delete();
        }
    }

    public static List<Map<String, Object>> getFilePath(){
        Controller controller = JbootControllerContext.get();
        List<UploadFile> file = controller.getFiles();
        FileUtils fileUtils = new FileUtils();
        List<Map<String, Object>> mapList = null;
        try {
            mapList = fileUtils.upload(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return mapList;
    }
}

6、java Stream()流的基本操作

import com.alibaba.fastjson.JSONObject;
import java.util.*;
import java.util.stream.Collectors;


public class Testconttrol {


    public static void main(String[] args) {

        List<String> strings = Arrays.asList("abc", "", "bc", "efg", "abcd","", "jkl");
        List<Integer> integers = Arrays.asList(1,2,2,13,4,15,6,17,8,19);
        // 计算空字符串
        System.out.println(strings.stream().filter(string -> !string.isEmpty()).count());
        //字符串长度为 3 的数量为
        System.out.println(strings.stream().filter(s -> s.length() == 3).count());

        //筛选后的列表
        System.out.println(strings.stream().filter(s -> s.length() == 3).collect(Collectors.toList()));
        // 删除空字符串
        System.out.println(strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.toList()));

		String collect = result.stream().map(d -> d.get("serial_num").toString()).collect(Collectors.joining(","));
        // 删除空字符串,并使用逗号把它们合并起来
        System.out.println(strings.stream().filter(s -> !s.isEmpty()).collect(Collectors.joining(",")));
        // 获取列表元素平方数
        System.out.println(integers.stream().map(integer -> integer*integer).distinct().collect(Collectors.toList()));
        System.out.println(integers.stream().map(integer -> integer*integer).collect(Collectors.toList()));

		Double amount = trueResult.stream().map(a -> new BigDecimal(a.get("amount").toString())).reduce(BigDecimal::add).map(BigDecimal::doubleValue).orElse(0d);

        IntSummaryStatistics intSummary = integers.stream().mapToInt((x)->x).summaryStatistics();
        //列表中最大的数
        System.out.println(intSummary.getMax());
        //列表中最小的数
        System.out.println(intSummary.getMin());
        //所有数之和
        System.out.println(intSummary.getSum());
        //平均数
        System.out.println(intSummary.getAverage());
        //随机数
        Random random = new Random();
        // 输出10个随机数
        random.ints().limit(10).sorted().forEach(System.out::println);

    }
    //List<Map<String,Object>>条件分组
    public void  test1(){
        List<Map<String,Object>> list2 = new ArrayList<>();
        Map<String,Object> map1 = new HashMap<>();
        map1.put("region", "410185");
        map1.put("positionText", "服务员");
        map1.put("urgent", "1");
        list2.add(map1);
        Map<String,Object> map2 = new HashMap<>();
        map2.put("region", "410100");
        map2.put("positionText", "按摩师");
        map2.put("urgent", "2");
        list2.add(map2);
        Map<String,Object> map3 = new HashMap<>();
        map3.put("region", "410100");
        map3.put("positionText", "服务员");
        map3.put("urgent", "2");
        list2.add(map3);
        Map<String,Object> map4 = new HashMap<>();
        map4.put("region", "410155");
        map4.put("positionText", "会计");
        map4.put("urgent", "1");
        list2.add(map4);
        List<Map<String, Object>> groupList = list2.stream().collect(Collectors.groupingBy(d -> d.get("region"))).entrySet()
                .stream().map(d -> {
                    Map<String, Object> map = new HashMap<>();
                    map.put("recruitList", d.getValue());
                    map.put("region", d.getKey());
                    return map;
                }).collect(Collectors.toList());

        System.out.println(JSONObject.toJSON(groupList));
    }
        //List排序
		value.getValue().sort(Comparator.comparing(
                        (Function<AdsDomesticRicePurchasePrice, Date>) BaseAdsDomesticRicePurchasePrice::getTime
                ).reversed());

}

7、BigDecimal加减乘除计算

//加法
BigDecimal result1 = num1.add(num2);
BigDecimal result12 = num12.add(num22);
 
//减法
BigDecimal result2 = num1.subtract(num2);
BigDecimal result22 = num12.subtract(num22);
 
//乘法
BigDecimal result3 = num1.multiply(num2);
BigDecimal result32 = num12.multiply(num22);
 
//绝对值
BigDecimal result4 = num3.abs();
BigDecimal result42 = num32.abs();
 
//除法
BigDecimal result5 = num2.divide(num1,20,BigDecimal.ROUND_HALF_UP);
BigDecimal result52 = num22.divide(num12,20,BigDecimal.ROUND_HALF_UP);

8、数字区间判断

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;

public class CheckBetweenUtils {
    /**
     * 判断data_value是否在interval区间范围内
     * @param data_value 数值类型的
     * @param interval 正常的数学区间,包括无穷大等,如:(1,3)、>5%、(-∞,6]、(125%,135%)U(70%,80%)
     * @return true:表示data_value在区间interval范围内,false:表示data_value不在区间interval范围内
     */
    public boolean isInTheInterval(String data_value,String interval) {
        //将区间和data_value转化为可计算的表达式
        String formula = getFormulaByAllInterval(data_value,interval,"||");
        ScriptEngine jse = new ScriptEngineManager().getEngineByName("JavaScript");
        try {
            //计算表达式
            return (Boolean) jse.eval(formula);
        } catch (Exception t) {
            return false;
        }
    }

    /**
     * 将所有阀值区间转化为公式:如
     * [75,80)   =》        date_value < 80 && date_value >= 75
     * (125%,135%)U(70%,80%)   =》        (date_value < 1.35 && date_value > 1.25) || (date_value < 0.8 && date_value > 0.7)
     * @param date_value
     * @param interval  形式如:(125%,135%)U(70%,80%)
     * @param connector 连接符 如:") || ("
     */
    private String getFormulaByAllInterval(String date_value, String interval, String connector) {
        StringBuffer buff = new StringBuffer();
        for(String limit:interval.split("U")){//如:(125%,135%)U (70%,80%)
            buff.append("(").append(getFormulaByInterval(date_value, limit," && ")).append(")").append(connector);
        }
        String allLimitInvel = buff.toString();
        int index = allLimitInvel.lastIndexOf(connector);
        allLimitInvel = allLimitInvel.substring(0,index);
        return allLimitInvel;
    }

    /**
     * 将整个阀值区间转化为公式:如
     * 145)      =》         date_value < 145
     * [75,80)   =》        date_value < 80 && date_value >= 75
     * @param date_value
     * @param interval  形式如:145)、[75,80)
     * @param connector 连接符 如:&&
     */
    private String getFormulaByInterval(String date_value, String interval, String connector) {
        StringBuffer buff = new StringBuffer();
        for(String halfInterval:interval.split(",")){//如:[75,80)、≥80
            buff.append(getFormulaByHalfInterval(halfInterval, date_value)).append(connector);
        }
        String limitInvel = buff.toString();
        int index = limitInvel.lastIndexOf(connector);
        limitInvel = limitInvel.substring(0,index);
        return limitInvel;
    }

    /**
     * 将半个阀值区间转化为公式:如
     * 145)      =》         date_value < 145
     * ≥80%      =》         date_value >= 0.8
     * [130      =》         date_value >= 130
     * <80%     =》         date_value < 0.8
     * @param halfInterval  形式如:145)、≥80%、[130、<80%
     * @param date_value
     * @return date_value < 145
     */
    private String getFormulaByHalfInterval(String halfInterval, String date_value) {
        halfInterval = halfInterval.trim();
        if(halfInterval.contains("∞")){//包含无穷大则不需要公式
            return "1 == 1";
        }
        StringBuffer formula = new StringBuffer();
        String data = "";
        String opera = "";
        if(halfInterval.matches("^([<>≤≥\\[\\(]{1}(-?\\d+.?\\d*\\%?))$")){//表示判断方向(如>)在前面 如:≥80%
            opera = halfInterval.substring(0,1);
            data = halfInterval.substring(1);
        }else{//[130、145)
            opera = halfInterval.substring(halfInterval.length()-1);
            data = halfInterval.substring(0,halfInterval.length()-1);
        }
        double value = dealPercent(data);
        formula.append(date_value).append(" ").append(opera).append(" ").append(value);
        String a = formula.toString();
        //转化特定字符
        return a.replace("[", ">=").replace("(", ">").replace("]", "<=").replace(")", "<").replace("≤", "<=").replace("≥", ">=");
    }

    /**
     * 去除百分号,转为小数
     * @param str 可能含百分号的数字
     * @return
     */
    private double dealPercent(String str){
        double d = 0.0;
        if(str.contains("%")){
            str = str.substring(0,str.length()-1);
            d = Double.parseDouble(str)/100;
        }else{
            d = Double.parseDouble(str);
        }
        return d;
    }
}

9、从互联网上下载图片并保存到本地服务器

import java.net.URL;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;

public class ImageDownloader {

    public static void main(String[] args) throws IOException {
        String imageUrl = "https://example.com/image.jpg"; // 图片地址
        String fileName = "image.jpg"; // 保存的文件名

        URL url = new URL(imageUrl);
        ReadableByteChannel channel = Channels.newChannel(url.openStream());

        // 创建目标文件
        File file = new File("path/to/save/" + fileName);
        FileOutputStream outputStream = new FileOutputStream(file);

        // 将文件内容从网络流写入本地文件
        outputStream.getChannel().transferFrom(channel, 0, Long.MAX_VALUE);

        // 关闭网络流和文件流
        channel.close();
        outputStream.close();

        System.out.println("图片已下载并保存到本地!");
    }
}

10、java邮件发送

import java.util.Properties;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class SendEmail {
    public static void main(String[] args) {

        // 设置邮件服务器的属性
        Properties properties = new Properties();
        properties.put("mail.smtp.host", "smtp.gmail.com"); // 例如Gmail的SMTP服务器
        properties.put("mail.smtp.port", "587"); // SMTP服务器端口号
        properties.put("mail.smtp.auth", "true"); // 需要身份验证
        properties.put("mail.smtp.starttls.enable", "true"); // 开启TLS加密

        // 获取会话对象
        Session session = Session.getInstance(properties, new javax.mail.Authenticator() {
            protected javax.mail.PasswordAuthentication getPasswordAuthentication() {
                // 设置发送邮件的账号和密码
                return new javax.mail.PasswordAuthentication("你的电子邮件地址", "你的电子邮件密码");
            }
        });

        try {
            // 创建邮件消息对象
            Message message = new MimeMessage(session);
            message.setFrom(new InternetAddress("你的电子邮件地址")); // 发件人
            message.setRecipients(Message.RecipientType.TO, InternetAddress.parse("接收邮件的地址")); // 收件人
            message.setSubject("邮件主题"); // 邮件主题
            message.setText("邮件内容"); // 邮件内容

            // 发送邮件
            Transport.send(message);

            System.out.println("邮件已成功发送!");

        } catch (MessagingException e) {
            throw new RuntimeException(e);
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值