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

标签 java file compilation

我正在尝试为 java 文件制作自己的 pretty-print ,类似于 JDoodle。我如何编译一个java类,给定它的位置作为字符串,或者它的内容作为字符串,以及给定std输入的文本文件,同时将输出记录为单独的字符串。抱歉,如果这看起来很麻烦。如有任何帮助,我们将不胜感激!

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

最佳答案

好的,我得到答案了。我使用Eclipse的编译器(因为我的学校笔记本电脑中没有JDK)来编译并使用processbuilder来运行生成的.class文件,使用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 以及要写入的输出文件。

关于java - 如何编译存储在字符串中的 Java 类,或者使用给定输入的路径?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468668/

相关文章:

c++ - 如何通过缓冲区大小来优化读写?

c - 在 Linux 上编译 OpenCL ICD 加载程序时出错

aix6.1 上的 python3.2 错误

java - 我们如何在java代码的帮助下设置类路径?

java - 使用反射读取类的字段时出错

java - 字符串格式化,如何为 'iiii' 和 'wwww' 提供相同的宽度

java - 减少我的 Android 应用程序资源的大小

java - AWS 无法验证提供的访问凭证(eclipse)

python - 如何将日志消息从多处理模块路由到文件?

scala - 有多个 `package` 声明会减慢编译器的速度吗?