针对如下情况,写了这个Java文件操作类:
1.有时候项目要求报文必须是XML格式并且节点为大写加下划线
2.第三方接口报文是xml格式,且字段带下划线
3.创建数据库表实体类
4.移出所有xml
由于手动修改比较费时且容易出错,所以写了这个工具类,代码如下:
package com.qufeng.cq.util;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang3.StringUtils;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
/**
* 操作XML注解
*@author qufeng
*@Date 2020年11月10日
*
*/
public class JavaFileUtils {
private static final String YYYY_MM_DD_HH_MM_SS_SSS ="yyyyMMddhhmmssSSS";
private static final String ENCODING = "UTF-8";
/**
* 添加XML注解 大写加下划线
* @param productPath 项目地址 为空的话取当前路径
* @param clazz
* @param backup 是否备份
* @throws IOException
*/
public static void addXmlUpperUnderLine(String productPath, Class<?> clazz, boolean backup) throws IOException{
productPath = StringUtils.isBlank(productPath) ? new File("").getAbsolutePath().toLowerCase() : productPath;
//根路径
String rootPath = productPath + "/src/main/java/";
//包路径
String packagePath = clazz.getPackage().getName().replaceAll("\\.", "/");
//类名
String className = clazz.getSimpleName();
//文件呢路径
String filePath = rootPath + "/" + packagePath + "/" + className + ".java";
Field[] dields = clazz.getDeclaredFields();
List<String> fieldNames = new ArrayList<>();
for(Field field : dields){
fieldNames.add(field.getName());
}
fieldNames.remove("serialVersionUID");//移出序列化属性
File file = new File(filePath);
List<String> lines = FileUtils.readLines(file, ENCODING);
if(dields.length > 0){
lines.add(2, "import javax.xml.bind.annotation.XmlElement;");
}
List<String> newLines = new ArrayList<>();
boolean firstWrap = true;//第一次添加wrapper包
for (String line : lines) {
String tempLine = line.trim();
//非空白行 且非注释行
if(!tempLine.equals("") && tempLine.indexOf("//") != 0){
String[] temp = tempLine.split(";")[0].split("=")[0].trim().split