【问题标题】:How to print java compiler error log using tools.jar compile method?如何使用 tools.jar 编译方法打印 java 编译器错误日志?
【发布时间】:2020-12-27 17:23:58
【问题描述】:

在我的idea 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));
    } 

【问题讨论】:

    标签: java compiler-errors tools.jar


    【解决方案1】:

    好吧,如果我的问题是正确的,这里有一个结果方法。 我认为这将与平台无关。

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

    【讨论】:

    • 如果我使用com.sun.tools.javac.Main.compile()方法,我可以在部署jar的时候在linux服务器打印编译日志吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-06
    • 1970-01-01
    • 2016-04-13
    • 2018-01-20
    • 1970-01-01
    • 2012-11-10
    • 1970-01-01
    相关资源
    最近更新 更多