gpt4 book ai didi

java - 如何使用tools.jar编译方法打印Java编译器错误日志?

转载 作者:行者123 更新时间:2023-12-03 07:38:06 26 4
gpt4 key购买 nike

在我的想法IDE中,我可以在控制台中看到带有红色字体的编译错误,但是当我在Linux服务器中部署jar时,却看不到编译日志,如何打印编译错误日志?

public static void main(String[] args) throws Exception { 
String compliePath="D:\\testFole";
String filename="D:\\test.java";
String[] arg = new String[] { "-d", compliePath, filename };
System.out.println(com.sun.tools.javac.Main.compile(arg));
}
enter image description here

最佳答案

Well if I got your question right, here is an approach to the outcome.I think this will be platform-independent.

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {

private static Process process;

public static void main(String[] args) {

runCommand();
getErrorMessage();

}


/**
* This method executes/runs the commands
*/
private static void runCommand()
{
File file = new File("D:\\\\test.java");

String changeDirectory = "cmd start cmd.exe /c cd D:\\";
String compile = " && javac D:\\test.java";
String run = " && java "+file.getName().replace(".java","");
String command = changeDirectory + compile + run;

try {
process = Runtime.getRuntime().exec(command);
}catch (IOException e){}
}



/**
* This method will get the errorStream from process
* and output it on the console.
*/
private static void getErrorMessage()
{

try (BufferedReader errorReader = new BufferedReader(new InputStreamReader(process.getErrorStream())))
{
String line;

if(errorReader.readLine() != null)
while ((line = errorReader.readLine()) != null)
System.out.println(line); //display error message

}catch (IOException e){}
}

}

关于java - 如何使用tools.jar编译方法打印Java编译器错误日志?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65468414/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com