附上垃圾代码(勿喷,只不过为了应付工作需求 ,百十来个service 都要创建对应的 controller的需求,复制实在吃不消,说明一下 就是简单的字符串替换操作)
ApplicationController
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
public class ApplicationController {
/**
* 根据 Service接口 生成 Controller 文件
*/
public static void main(String[] args) throws IOException {
String[] suffixPaths = {
"gray",
"group",
"home"
};
for (String suffixPath : suffixPaths) {
run(suffixPath);
}
System.out.println("操作成功");
}
private static void run(String suffixPath) {
// 读取目录 接口文件所在目录
String readPath = "D:\\Projects\\ideaProjects\\联想车辆\\aoac_dev\\aoac\\thinkiot-mno\\thinkiot-sdk\\src\\main\\java\\com\\lenovo\\thinkiot\\interfaces\\" +
suffixPath;
// controller生成文件当值目录
String writePath = "D:\\Projects\\ideaProjects\\createTest\\src\\main\\resources\\controller\\" + suffixPath + "\\";
// controller类的包名
String packageName = "package com.lenovo.thinkiot.controller";
List<File> fileList = new ArrayList<>();
createFile(writePath);
getFile(readPath, fileList);
for (File file : fileList) {
String fileName = file.getName();
String oldClassName = file.getName().substring(0, file.getName().lastIndexOf("."));
String oldcontent = readFileByLines(file.getPath());
System.out.print("文件名:" + fileName);
// System.out.println("类名:" + oldClassName);
// System.out.println("内容:\n" + oldcontent);
try {
StringBuffer newContent = new StringBuffer();
String[] split = file.getPath().split("\\\\");
String pack = split[split.length - 2];
String newPackage = packageName + "." + pack + ";";
String newClassName = oldClassName.replace("Service", "Controller");
// 读取内容
BufferedReader reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 0;
while ((tempString = reader.readLine()) != null) {
line++;
if (line == 1) {
// 修改包
newContent.append(newPackage + "\n\n");
newContent.append("import org.springframework.stereotype.Controller;\n");
newContent.append("import org.springframework.beans.factory.annotation.Autowired;\n");
newContent.append("import org.springframework.web.bind.annotation.PostMapping;\n");
newContent.append("import org.springframework.web.bind.annotation.RequestMapping;\n");
newContent.append("import org.springframework.web.bind.annotation.RequestBody;\n");
newContent.append("import org.springframework.web.bind.annotation.RequestParam;\n");
String[] params = file.getPath().split("\\\\");
StringBuffer attrs = new StringBuffer("import ");
for (int i = 0; i < params.length; i++) {
String param = params[i].trim();
if (param.equals("com")) {
for (int j = i; j < params.length; j++) {
if (params[j].contains(".")) {
params[j] = params[j].substring(0, params[j].indexOf("."));
}
attrs.append(params[j]);
if (j != params.length - 1) {
attrs.append(".");
} else {
attrs.append(";\n");
}
}
break;
}
}
newContent.append(attrs);
continue;
}
if (tempString.contains("/**")) {
String temp = tempString;
while (!temp.contains("*/")) {
newContent.append(temp + "\n");
temp = reader.readLine();
}
newContent.append(temp + "\n");
continue;
}
if (tempString.contains("public interface ")) {
// 添加新的 import包 和 @controller
String prefix = "@Controller\n" +
"@RequestMapping(\"/" + toLowerCaseFirstOne(newClassName.replace("Controller", "")) + "\")\n";
tempString = prefix + tempString;
// 修改接口为类
tempString = tempString.replace("interface", "class");
// 设置类名称
tempString = tempString.replace(oldClassName, newClassName);
// 设置 @Autowired
tempString = tempString + "\n\n\t@Autowired\n";
tempString = tempString + "\tprivate " + oldClassName + " " + toLowerCaseFirstOne(oldClassName) + ";\n";
newContent.append(tempString + "\n");
continue;
}
if (tempString.trim().length() > 2 && tempString.trim().startsWith("//")) {
continue;
}
if (tempString.trim().length() > 1 && tempString.trim().endsWith(",")) {
String twoLineCon = null;
do {
twoLineCon = reader.readLine();
tempString = tempString + twoLineCon.trim();
} while (!twoLineCon.contains(";"));
}
if (tempString.contains(";") && !tempString.contains("import ") && !tempString.contains("* ")) {
// 设置方法内容(代码块)
boolean idVoid = tempString.contains("void ");
tempString = "\tpublic " + tempString.trim();
tempString = tempString.substring(0, tempString.indexOf(";"));
int i1 = tempString.indexOf(")");
int i2 = tempString.indexOf("(");
if (i1 - i2 > 1) {
// 设置方法形参
String funAttr = "";
String funAttrStr = tempString.substring(tempString.indexOf("(") + 1, tempString.indexOf(")"));
String[] split1 = funAttrStr.split(",");
int i = 0;
for (String str : split1) {
if (checkType(str)) {
// 复炸对象
funAttr = funAttr + "@RequestBody " + str;
} else {
funAttr = funAttr + "@RequestParam " + str;
}
if (i != split1.length - 1) {
funAttr = funAttr + ", ";
}
i++;
}
tempString = tempString.replace(funAttrStr, funAttr);
}
tempString = tempString + " {\n";
// 获取方法名称
String fun = null;
int endIndex = tempString.indexOf("(");
String substring = null;
try {
substring = tempString.substring(0, endIndex);
} catch (Exception e) {
throw new IOException("错误文件:" + file.getPath() + " 错误内容:" + tempString);
}
char[] chars = substring.toCharArray();
for (int i = chars.length - 1; i >= 0; i--) {
if (Character.toString(chars[i]).equals(" ")) {
fun = substring.substring(i + 1, endIndex);
break;
}
}
String con = "\t\t" + (!idVoid ? "return " : "") + (toLowerCaseFirstOne(oldClassName)).trim() + "." + fun.trim();
String tmp = tempString.substring(endIndex + 1, (tempString.indexOf(")")));
String[] params = tmp.split(",");
StringBuffer attrs = new StringBuffer();
for (int i = 0; i < params.length; i++) {
String param = params[i].trim();
param = param.replace("@RequestParam", "");
param = param.replace("@RequestBody", "");
param = param.trim();
int num = param.indexOf(" ");
if (num == -1) {
continue;
}
param = param.substring(num);
param = param.substring(param.indexOf(" "));
params[i] = param;
attrs.append(param.trim());
if (i != params.length - 1) {
attrs.append(", ");
}
}
tmp = con + "(" + attrs.toString().trim() + ");\n";
tempString = tempString + tmp;
String postRequest = "\t@PostMapping(\"/" + toLowerCaseFirstOne(fun.trim()) + "\")\n";
tempString = postRequest + tempString;
newContent.append(tempString + "\t}\n");
continue;
}
newContent.append(tempString + "\n");
}
reader.close();
// 写入
FileExport.creatTxtFile(writePath, newClassName + ".java");
FileExport.writeTxtFile(newContent.toString());
} catch (IOException e) {
System.out.println(" - 失败");
e.printStackTrace();
}
System.out.println(" - 成功");
}
}
private static void createFile(String writePath) {
File file = new File(writePath);
if (!file.exists() && !file.isDirectory()) {
file.mkdir();
}
}
private static boolean checkType(String str) {
String[] types = {"Integer",
"Double",
"Float",
"Long",
"Short",
"Byte",
"Boolean",
"Character",
"String",
"Date",
"int", "double", "long", "short", "byte", "boolean", "char", "float"};
List<String> list = Arrays.asList(types);
boolean contains = !list.contains(str.trim().split(" ")[0]);
return contains;
}
// 给定目录的绝对路径,获取该目录下的所有文件(子目录的文件也可递归得到)
public static void getFile(String path, List<File> fileList) {
// File对象 可以是文件或者目录
File file = new File(path);
File[] array = file.listFiles();
for (int i = 0; i < array.length; i++) {
if (array[i].isFile()) {
fileList.add(array[i]);
} else if (array[i].isDirectory()) {
getFile(array[i].getPath(), fileList);
}
}
}
/**
* 以行为单位读取文件,常用于读面向行的格式化文件
*/
public static String readFileByLines(String fileName) {
File file = new File(fileName);
BufferedReader reader = null;
StringBuffer con = new StringBuffer();
try {
reader = new BufferedReader(new FileReader(file));
String tempString = null;
int line = 1;
// 一次读入一行,直到读入null为文件结束
while ((tempString = reader.readLine()) != null) {
// 显示行号
// System.out.println("line " + line + ": " + tempString);
con.append(tempString);
con.append("\n");
line++;
}
reader.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e1) {
}
}
}
return con.toString();
}
//首字母转小写
public static String toLowerCaseFirstOne(String s) {
if (Character.isLowerCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();
}
//首字母转大写
public static String toUpperCaseFirstOne(String s) {
if (Character.isUpperCase(s.charAt(0)))
return s;
else
return (new StringBuilder()).append(Character.toUpperCase(s.charAt(0))).append(s.substring(1)).toString();
}
}
FileExport 文件操作
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
public class FileExport {
private static String filenameTemp;
public static void main(String[] args) {
// FileExport.creatTxtFile("你好");
// FileExport.writeTxtFile("你好");
}
/**
* 创建文件
*
* @throws IOException
*/
public static boolean creatTxtFile(String path, String name) throws IOException {
boolean flag = false;
filenameTemp = path + name;
File filename = new File(filenameTemp);
if (!filename.exists()) {
filename.createNewFile();
flag = true;
}
return flag;
}
/**
* 写文件
*
* @param newStr
* 新内容
* @throws IOException
*/
public static boolean writeTxtFile(String newStr) throws IOException {
// 先读取原有文件内容,然后进行写入操作
boolean flag = false;
String filein = newStr + "\r\n";
String temp = "";
FileInputStream fis = null;
InputStreamReader isr = null;
BufferedReader br = null;
FileOutputStream fos = null;
PrintWriter pw = null;
try {
// 文件路径
File file = new File(filenameTemp);
// 将文件读入输入流
fis = new FileInputStream(file);
isr = new InputStreamReader(fis);
br = new BufferedReader(isr);
StringBuffer buf = new StringBuffer();
// 保存该文件原有的内容
for (int j = 1; (temp = br.readLine()) != null; j++) {
buf = buf.append(temp);
// System.getProperty("line.separator")
// 行与行之间的分隔符 相当于“\n”
buf = buf.append(System.getProperty("line.separator"));
}
buf.append(filein);
fos = new FileOutputStream(file);
pw = new PrintWriter(fos);
pw.write(buf.toString().toCharArray());
pw.flush();
flag = true;
} catch (IOException e1) {
// TODO 自动生成 catch 块
throw e1;
} finally {
if (pw != null) {
pw.close();
}
if (fos != null) {
fos.close();
}
if (br != null) {
br.close();
}
if (isr != null) {
isr.close();
}
if (fis != null) {
fis.close();
}
}
return flag;
}
}
标签:String,Servie,接口,Controller,tempString,import,null,new,append From: https://blog.51cto.com/u_14671216/6397678