有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

文件如何编译存储在字符串中的Java类,或者如何使用给定输入的路径?

我正在尝试为java文件制作自己的漂亮打印,类似于JDoodle。我如何编译一个java类,给定它的位置作为一个字符串,或者它的内容作为一个字符串,以及给定一个用于std输入的文本文件,同时将输出记录为一个单独的字符串。如果这看起来很麻烦,很抱歉。感谢您的帮助

编辑:我确实知道java.tools.ToolProviderTool,但即使它是解决方案,我也不知道如何处理它,因为文档对我来说太混乱,或者太稀疏


共 (1) 个答案

  1. # 1 楼答案

    好的,我得到了答案。我使用Eclipse的编译器(因为我的学校笔记本电脑中没有JDK)进行编译,并使用processbuilder运行生成的代码。类文件,使用redirectOutput将输出重定向到我读取以获取输出的文件。谢谢-这是代码

    /*PRETTYPRINT*/
    /*
     * Code to HTML
     * Uses highlightjs in order to create a html form for your code, you can also give inputs and outputs
     * */
    
    import java.io.File;
    import java.io.FileNotFoundException;
    import java.io.IOException;
    import java.io.PrintWriter;
    import java.nio.file.Files;
    import java.nio.file.Paths;
    
    public class PrettyPrint {
        public static void main(String[] args) throws FileNotFoundException{
            String javaFile = readFile(args[0]);
            String commandLine = readFile(args[1]);
            String output = readFile(args[2]);
            String html = "<!DOCTYPE html>\n"
                    +"<html>\n"
                    +"<head>"
                    +"<link rel=\"stylesheet\" href=\"highlightjs/styles/a11y-dark.css\" media= \"all\">\r\n"
                    +"<script src=\"highlightjs/highlight.pack.js\"></script>\r\n"
                    +"<script>hljs.initHighlightingOnLoad();</script>"
                    +"<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js\" integrity=\"sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/\" crossorigin=\"anonymous\"></script>\r\n"
                    +"<script src=\"https://cdn.jsdelivr.net/npm/html2canvas@1.0.0-rc.5/dist/html2canvas.min.js\"></script>"
                    +"<meta charset=\"utf-8\">"
                    +"<style>code{overflow-x: visible;}body{background-color:#888888;color:#444444;}h1{text-align:center;color:#444444;}</style>"
                    +"</head>"
                    +"<body style=\"font-family: 'Consolas';\">\n"
                    +"<h1 style=\"text-align: center\">Java Code</h1>"
                    +"<pre><code class=\"java\" style=\"overflow-x:visible\">"
                    +toHTML(javaFile)
                    +"</code></pre>"
                    +"<br>\n"
                    +"<h1>Inputs</h1>"
                    +"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
                    +toHTML(commandLine)
                    +"</code></pre>"
                    +"<br>\n"
                    +"<h1>Output</h1>"
                    +"<pre><code class = \"nohighlight hljs\" style=\"overflow-x:visible\">"
                    +toHTML(output)
                    +"</code></pre>"
                    +"</body>\n"
                    +"<script>"
                    +"console.log(document.body.innerHTML);"
                    //+String.format("function print(){const filename='%s';html2canvas(document.body).then(canvas=>{let pdf = new jsPDF('p','mm', 'a4');pdf.addImage(canvas.toDataURL('image/png'), 'PNG', 0, 0, 1000, 1000);pdf.save(filename);});}print();",args[3].substring(args[3].lastIndexOf('/')+1, args[3].length()-4)+"pdf")
                    + "</script>"
                    +"</html>\n";
            //System.out.println(html);
            try {
                File file = new File("output.html");
                PrintWriter fileWriter = new PrintWriter(file);
                fileWriter.print(html);
                fileWriter.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
    
        }
        public static String toHTML(String str) {
            String html = str;
            html = html.replace("&","&amp;");
            html = html.replace("\"", "&quot;");
            html = html.replace("\'", "&apos;");
            html = html.replace("<", "&lt;");
            html = html.replace(">", "&gt;");
            //html = html.replace("\n", "<br>");
            html = html.replace("\t", "&emsp;&emsp;");
            html+= "<br>";
    
            return html;
        }
        public static String readFile(String filePath)
        {
            String content = "";
            try
            {
                content = new String ( Files.readAllBytes( Paths.get(filePath) ) );
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
            return content;
    
        }
    }
    
    
    /**PROCESSBUILDEREXAMPLE**/
    
    import java.io.*;
    import org.eclipse.jdt.core.compiler.CompilationProgress;
    import org.eclipse.jdt.core.compiler.batch.BatchCompiler;
    
    public class ProcessBuilderExample {
        private static String JAVA_FILE_LOCATION;
    
        public static void main(String args[]) throws IOException{
            JAVA_FILE_LOCATION = args[0];
            CompilationProgress progress = null;
            BatchCompiler.compile(String.format("-classpath rt.jar %s",args[0]), new PrintWriter(System.out), new PrintWriter(System.err), progress);
    
            Process process = new ProcessBuilder("java", "-cp",
                    JAVA_FILE_LOCATION.substring(0,JAVA_FILE_LOCATION.lastIndexOf("\\")),
                    JAVA_FILE_LOCATION.substring(JAVA_FILE_LOCATION.lastIndexOf("\\")+1,JAVA_FILE_LOCATION.length()-5))
                    .redirectInput(new File(args[1]))
                    .redirectOutput(new File(args[2])).start();
            try {
                process.waitFor();
                PrettyPrint.main(args);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
    }
    

    将这2个参数保存在同一文件夹中,并使用3个参数运行processbuilderexample。代码的loc、输入文件的loc和要写入的输出文件