Java 更改目录和编译 LaTeX 源代码的运行时命令不起作用

Java Runtime Command to Change Directory & Compile LaTeX Source Not Working

我目前正在开发一个 java 项目,该项目使用 LaTeX 源代码自动生成文本文件。这些文件被写入硬盘驱动器的已知目录。我不想自己手动将 LaTeX 源代码编译成 pdf,而是想使用 Runtime.getRunTime().exec().

我下载并安装了 BasicTeX。我知道它工作正常。我可以在新终端 window 中调用以下命令,并且 pdf 已正确生成且没有错误。像这样:

Kyles-MacBook-Pro:~ kylekrol$ cd Documents/folder/Report
Kyles-MacBook-Pro:Report kylekrol$ pdflatex latexDocument.txt

所以我只是在我的程序关闭之前尝试使用以下代码来编译pdf:

private static void compileLatexMac(String path) {
    String s = null;
    try {
        System.out.println("cd " + path.substring(0, path.length() - 1) + " && pdflatex latexDocument.txt");

        Process p = Runtime.getRuntime().exec("cd " + path.substring(0, path.length() - 1) + " && pdflatex latexDocument.txt");
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
        BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));

        System.out.println("outputs:");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        System.out.println("errors:");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.exit(-1);
    }
}

当我 运行 我得到的只有以下内容,没有 pdf 或日志文件。

cd /Users/kylekrol/Documents/folder/Report && pdflatex latexDocument.txt
outputs:
errors:

我不太确定该怎么做或为什么它不起作用 - 特别是因为我可以从终端调用 cd /Users/kylekrol/Documents/folder/Report && pdflatex latexDocument.txt 并且它 运行s 根据需要。

如果有人能指出我在这里遗漏了什么,那就太好了。谢谢!


当我双击 jar 文件 运行 时,我使用三参数 exec() 命令 运行 解决了更多问题。我通过调用以下命令来修复此问题,该命令使用额外的 pdflatex 参数且仅使用绝对路径。

Runtime.getRuntime().exec("pdflatex -output-directory=" + path.substring(0, path.length() - 1) + " " + path + "latexDocument.txt");

运算符 && 由 shell 扩展。 Runtime.exec 不会扩展此运算符,而只是尝试以命令行的其余部分作为参数来执行 cd 命令。因此,您的 pdflatex 命令永远不会是 运行.

如果您想 运行 pdflatex 与特定的工作目录,请使用 Runtime.execthree-argument version