java工作记录

本文介绍了在SpringBoot项目中如何进行时间格式化、Map和List的排序操作,包括BigDecimal的除法与精度控制,异常信息的收集,以及使用反射获取方法形参和MyBatis-Roo配置多数据源的方法。

字符串

int转string 位数不够前面补0

public static String int2Str (Integer val,Integer ws) {
	int min = 1;
	for (int i = 0; i < ws; i++) {
		min = min * 10;
	}
	if (val >= min) {
		return val.toString();
	}
	String intStr = val.toString();
	int length = intStr.length();
	String add = "";
	for (int i = 0; i < ws - length; i++) {
		add = add + "0";
	}
	return add + intStr;
}

驼峰修改为下划线

public static String camelToSnake(String camelCase) {
	StringBuilder result = new StringBuilder();
	for (char c : camelCase.toCharArray()) {
		if (Character.isUpperCase(c)) {
			result.append('_').append(Character.toLowerCase(c));
		} else {
			result.append(c);
		}
	}
	return result.toString();
}

时间格式化

@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")//入参格式化 
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
//出参格式化,8为标准时区和北京时间的差异 
private Date birthday;

集合

Map根据value排序

Map<String,Double> upMap = new HashMap<>();
upMap.put("aa",2.5);
upMap.put("bb",1.5);
upMap.put("cc",3.5);
upMap.put("dd",0.5);
Map<String,Double> upResult = new HashMap<>();
upMap.entrySet()
    .stream()
    //降序排序
    .sorted(Map.Entry.<String,Double>comparingByValue().reversed())
    .forEachOrdered(d->upResult.put(d.getKey(),d.getValue()));

List根据其中一个值排序

List<Map<String, Object>> list = new ArrayList<>();
List<Map<String, Object>> sortList = list.stream()
    .sorted(Comparator.comparing(d -> (BigDecimal) d.get("每万人口现案数")))
    .collect(Collectors.toList());
sortList = CollectionUtil.reverse(sortList);

对象列表转为树形结构

public class Test {
    public static void main(String[] args) {
        List<Node> nodeList = new ArrayList<Node>() {{
            add(new Node("1","0"));
            add(new Node("2","1"));
            add(new Node("3","1"));
            add(new Node("4","2"));
            add(new Node("5",""));
        }};
        List<Node> nodes = buildTree(nodeList);
        System.out.println(JSONObject.toJSONString(nodes));
    }
    private static List<Node> buildTree(List<Node> nodeList) {
        for (Node vo : nodeList) {
            String parentId = vo.getParentId();
            if (StringUtils.isNotEmpty(parentId)) {
                for (Node data : nodeList) {
                    if (data.getId().equals(parentId)) {
                        vo.setIsChild(true);
                        List<Node> list = data.getChildren();
                        if (list == null) {
                            list = new ArrayList<>();
                        }
                        list.add(vo);
                        data.setChildren(list);
                        break;
                    }
                }
            }
        }
        return nodeList.stream().filter(d -> !d.getIsChild()).collect(Collectors.toList());
    }
}
@Data
class Node {
    public Node (String id,String parentId) {
        this.id = id;
        this.parentId = parentId;
    }
    private String id;
    private String parentId;
    private List<Node> children;
    private Boolean isChild = false;
}

字符串列表比对

public class test {
    public static CompareVO compareList(List<String> oldList, List<String> newList) {
        CompareVO result = new CompareVO();
        List<String> addList = new ArrayList<>();
        List<String> removeList = new ArrayList<>();
        List<String> retainList = new ArrayList<>();
        for (String id : oldList) {
            if (!newList.contains(id)) {
                removeList.add(id);
            } else {
                retainList.add(id);
            }
        }
        for (String id : newList) {
            if (!oldList.contains(id)) {
                addList.add(id);
            }
        }
        result.setAddList(addList);
        result.setRemoveList(removeList);
        result.setRetainList(retainList);
        return result;
    }
}
@Data
class CompareVO {
    // 需要添加
    private List<String> addList;
    // 需要删除
    private List<String> removeList;
    // 保持
    private List<String> retainList;
}

BigDecimal

除法和保留两位小数

BigDecimal bigDecimal = new BigDecimal(o.toString());
bigDecimal = bigDecimal.divide(new BigDecimal(10000));
//四舍五入保留两位小数
bigDecimal = bigDecimal.setScale(2, RoundingMode.HALF_UP);
System.out.println(bigDecimal.toString());

BigDecimal bigDecimal = new BigDecimal("100");
BigDecimal bigDecima2 = new BigDecimal("3");
//除法需要加入四舍五入和保留小数,否则会出现无限小数
//java.lang.ArithmeticException: 
//Non-terminating decimal expansion; 
//no exact representable decimal result.
System.out.println(bigDecimal.divide(bigDecima2,4,RoundingMode.HALF_UP));

计算百分比

/**
 * 计算百分比
 * @param val 数量
 * @param total 总数
 * @param scale 保留几位小数(默认2)
 * @return
 */
public static String calPercen(Integer val, Integer total,Integer scale) {
	if (total < 1) {
		return "";
	}
	if (scale == null) {
		scale = 2;
	}
	return new BigDecimal(val)
		.divide(new BigDecimal(total), scale + 2, BigDecimal.ROUND_HALF_UP)
		.multiply(new BigDecimal(100))
		.setScale(scale, BigDecimal.ROUND_HALF_UP)
		.toString() + "%";
}

异常

异常信息收集

public static void main(String [] args){
    try {
        int i = 0;
        System.out.println(1/i);
    }catch (Exception e){
        StringWriter writer = new StringWriter();
        e.printStackTrace(new PrintWriter(writer,true));
        System.out.println(writer.getBuffer().toString());
    }
}

获取路径

在这里插入图片描述

  • class.getResource:该方法接收一个表示文件路径的参数,返回一个URL对象,该URL对象表示的name指向的那个资源(文件)。绝对路径的话,根目录符号/是代表项目路径而不是磁盘的根目录
App.class.getResource('innerFile.txt')
App.class.getResource('/test/test/innerFile.txt')
  • classLoader.getResource:接收一个表示路径的参数,返回一个URL对象,该URL对象表示name对应的资源(文件)。该方法只能接收一个相对路径,不能接收绝对路径如/xxx/xxx。并且,接收的相对路径是相对于项目的包的根目录来说的。
App.class.getClassLoader().getResource('test/test/innerFile.txt')

springBoot项目常用方法

  • 获取当前项目的地址
String path = System.getProperty("user.dir");
// D:\work\test
  • 获取classes目录的绝对路径
String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
String path = ResourceUtils.getURL("classespath:").getPath();
// D:/work/test/target/classes/

反射

获取方法形参

public static void main(String [] args){
/**
* 不可以通过注入的对象获取class对象
* dlwaService.getClass().getMethods();
* jdk8以上才可以
*/
Method[] methods = DlwaService.class.getMethods();
for (Method method : methods) {
    DefaultParameterNameDiscoverer discoverer = new DefaultParameterNameDiscoverer();
    String[] parameterNames = discoverer.getParameterNames(method);
    for (String parameterName : parameterNames) {
    //输出方法形参名称
    //就可以根据形参名称来对参数进行排序
    System.out.println(parameterName);
    }
}
}

统计时间轴

import lombok.Data;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class test {

    public static List<StatisticsVO> generateDaysWeek(String startDate, String endDate) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> dates = findDates(format.parse(startDate), format.parse(endDate), Calendar.DATE);
        List<StatisticsVO> result = new ArrayList<>();
        String[] week = {"周一", "周二", "周三", "周四", "周五", "周六", "周日"};
        for (int i = 0; i < dates.size(); i++) {
            Date date = dates.get(i);
            StatisticsVO vo = new StatisticsVO();
            vo.setSj(format.format(date));
            vo.setSjName(week[i]);
            result.add(vo);
        }
        return result;
    }

    public static List<StatisticsVO> generateDaysMonth(String startDate, String endDate) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> dates = findDates(format.parse(startDate), format.parse(endDate), Calendar.DATE);
        List<StatisticsVO> result = new ArrayList<>();
        for (int i = 0; i < dates.size(); i++) {
            Date date = dates.get(i);
            StatisticsVO vo = new StatisticsVO();
            vo.setSj(format.format(date));
            vo.setSjName(i + 1 + "号");
            result.add(vo);
        }
        return result;
    }

    public static List<StatisticsVO> generateDaysYear(String startDate, String endDate) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM");
        DateFormat formatName = new SimpleDateFormat("M月");
        List<Date> dates = findDates(format.parse(startDate), format.parse(endDate), Calendar.MONTH);
        List<StatisticsVO> result = new ArrayList<>();
        for (int i = 0; i < dates.size(); i++) {
            Date date = dates.get(i);
            StatisticsVO vo = new StatisticsVO();
            vo.setSj(format.format(date));
            vo.setSjName(formatName.format(date));
            result.add(vo);
        }
        return result;
    }

    public static List<StatisticsVO> generateDaysTime(String startDate, String endDate) throws ParseException {
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        List<Date> dates = findDates(format.parse(startDate), format.parse(endDate), Calendar.DATE);
        List<StatisticsVO> result = new ArrayList<>();
        for (int i = 0; i < dates.size(); i++) {
            Date date = dates.get(i);
            StatisticsVO vo = new StatisticsVO();
            vo.setSj(format.format(date));
            vo.setSjName(vo.getSj());
            result.add(vo);
        }
        return result;
    }

    private static List<Date> findDates(Date dBegin, Date dEnd, int rules) {
        List lDate = new ArrayList();
        if (dEnd.before(dBegin)) {
            return lDate;
        }
        lDate.add(dBegin);
        Calendar calBegin = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calBegin.setTime(dBegin);
        Calendar calEnd = Calendar.getInstance();
        // 使用给定的 Date 设置此 Calendar 的时间
        calEnd.setTime(dEnd);
        // 测试此日期是否在指定日期之后
        while (dEnd.after(calBegin.getTime())) {
            // 根据日历的规则,为给定的日历字段添加或减去指定的时间量
            calBegin.add(rules, 1);
            lDate.add(calBegin.getTime());
        }
        return lDate;
    }
}
@Data
class StatisticsVO {
    // yyyy-MM-dd
    private String sj;
    // 周一、周二 或者 一月 二月 或者 一号 二号
    private String sjName;
    private Integer num;
}

通过实体类获取列名称

import com.baomidou.mybatisplus.annotation.TableField;
import com.ruoyi.common.excel.utils.ExcelUtil;
import lombok.Data;

import java.io.File;
import java.io.FileOutputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.List;

public class Test {
    public static void main(String[] args) {
        String packageFilePath = "D:\\app\\idea\\workspace\\test\\test\\src\\main\\java\\com\\src\\test\\entity";
        String packagePath = "com.src.test.entity";
        exportSql(packageFilePath,packagePath);
    }
    private static void exportSql(String packageFilePath,String packagePath) {
        File packageFile = new File(packageFilePath);
        List<String> classList = new ArrayList<>();
        for (File file : packageFile.listFiles()) {
            String className = file.getName();
            className = className.substring(0,className.lastIndexOf("."));
            classList.add(className);
        }
        classList.sort(String.CASE_INSENSITIVE_ORDER);
        List<Colunnn> columnList = new ArrayList<>();
        for (String s : classList) {
            try {
                List<String> tempList = new ArrayList<>();
                Class clz = Class.forName(packagePath + "." + s);
                if (s.endsWith("PO")) {
                    s = s.replaceAll("PO","");
                }
                Field[] declaredFields = clz.getDeclaredFields();
                for (Field field : declaredFields) {
                    if (Modifier.isStatic(field.getModifiers())) {
                        continue;
                    }
                    TableField annotation = field.getAnnotation(TableField.class);
                    if (annotation == null || annotation.exist()) {
                        Colunnn colunnn = new Colunnn();
                        colunnn.setTableName(camelToSnake(s).substring(1));
                        String s1 = camelToSnake(field.getName());
                        colunnn.setColumnName(s1);
                        tempList.add(s1);
                        columnList.add(colunnn);
                    }
                }
                Class superclass = clz.getSuperclass();
                while (!superclass.getSimpleName().equals("Object")) {
                    Field[] declaredFields1 = superclass.getDeclaredFields();
                    for (Field field : declaredFields1) {
                        if (Modifier.isStatic(field.getModifiers())) {
                            continue;
                        }
                        TableField annotation = field.getAnnotation(TableField.class);
                        if (annotation == null || annotation.exist()) {
                            Colunnn colunnn = new Colunnn();
                            colunnn.setTableName(camelToSnake(s).substring(1));
                            String s1 = camelToSnake(field.getName());
                            if (!tempList.contains(s1)) {
                                colunnn.setColumnName(s1);
                                tempList.add(s1);
                                columnList.add(colunnn);
                            }
                        }
                    }
                    superclass = superclass.getSuperclass();
                }
            }catch (Exception e) {
                e.printStackTrace();
            }
        }
        try {
            File xlsx = new File(packageFilePath + "\\sql.xlsx");
            FileOutputStream fileOutputStream = new FileOutputStream(xlsx);
            ExcelUtil.exportExcel(columnList, "sheet0",
                Colunnn.class, fileOutputStream);
            fileOutputStream.flush();
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("end");
    }
    private static String camelToSnake(String camelCase) {
        StringBuilder result = new StringBuilder();
        for (char c : camelCase.toCharArray()) {
            if (Character.isUpperCase(c)) {
                result.append('_').append(Character.toLowerCase(c));
            } else {
                result.append(c);
            }
        }
        return result.toString();
    }
}
@Data
class Colunnn {
    String tableName;
    String columnName;
}

若依

配置多数据源

若依配置多数据源,分别为不同数据库时示例

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值