微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

在我的idea IDE中,在console中可以看到红色字体的编译错误。但是在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

解决方法

好吧,如果我答对了你的问题,这里有一个解决结果的方法。 我认为这将与平台无关。

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){}
     }

}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。