proto文件编译工具类和编译后的文件

This commit is contained in:
thesai 2024-02-05 15:45:16 +08:00
parent 294c8f3a44
commit 1111d29fd0
9 changed files with 80 additions and 0 deletions

80
src/Compiler.java Normal file
View File

@ -0,0 +1,80 @@
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
public class Compiler {
static String I;
public static void main(String[] args) {
String basePath = System.getProperty("user.dir");
String protocPath = String.join(File.separator, basePath, "rtss-message", "protoc-23.1", "bin", "win64", "protoc.exe");
String protoFolderPath = String.join(File.separator, basePath, "rtss-message", "proto");
String outputDirectory = String.join(File.separator, basePath, "src", "main", "java");
StringBuilder sb = new StringBuilder();
File dir = new File(protoFolderPath);
buildI(dir, sb);
I = sb.toString();
recursiveCompile(protocPath, dir, outputDirectory);
}
private static void buildI(File file, StringBuilder sb) {
if (file.isDirectory()) {
sb.append(" -I=");
sb.append(file.getAbsolutePath());
File[] files = file.listFiles();
if (files == null) {
return;
}
for (File f : files) {
buildI(f, sb);
}
}
}
public static void recursiveCompile(String protocPath, File file, String outputDirectory) {
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files == null) {
return;
}
for (File f : files) {
recursiveCompile(protocPath, f, outputDirectory);
}
} else {
compiler(protocPath, outputDirectory, file.getAbsolutePath());
}
}
private static void compiler(String protocPath, String outputDirectory, String protoPath) {
try {
// 构建 protoc 命令
String command = protocPath + I + " --java_out=" + outputDirectory + " " + protoPath;
System.out.println(command);
// 在命令行运行 protoc 命令
Process process = Runtime.getRuntime().exec(command);
// 读取并打印输出
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
// 等待进程完成
int exitCode = process.waitFor();
if (exitCode == 0) {
System.out.println("Proto file compilation successful.");
} else {
System.err.println("Error during proto file compilation.");
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}