0

我编写了一个用 Java 实现的 PDF 生成器,并使用 PowerShell 脚本来编译 TEX 文件latexmk。生成命令的一个示例是powershell.exe -NoProfile -NoLogo "&'C:\path\to\scripts\compileTex.ps1' 'C:\path\to\workingDir' 'filename.tex'". 如果我在命令中手动执行此命令,cmd将编译 TEX 文件并正确返回。当我通过 Java 调用此脚本时,它不会返回。我阅读了许多其他建议< NUL在命令末尾添加的问题。我通过显式关闭进程的输入流来做到这一点。latexmk结果是所有 PowerShell 脚本都正确返回,但带有命令的脚本除外。

我使用以下 PowerShell 脚本进行编译:

param(
    [Parameter(Mandatory = $true)][string] $workingDir,
    [Parameter(Mandatory = $true)][string] $texFileName
)

if (Test-Path -LiteralPath "$workingDir") {
    cd "$workingDir"
    if (Test-Path -LiteralPath "$texFileName") {
        $texFileBaseName = $texFileName.Trim(".tex")
        latexmk -nobibtex -norc -pdf -jobname="$texFileBaseName" "$texFileName" # FIXME This call leads to a timeout
    } else {
        Write-Error "Could not find \"$texFileName\""
    }
} else {
    Write-Error "The working directory \"$workingDir\" does not exist"
}

我使用下面的 Java 代码片段来调用这个脚本:

        StringJoiner innerCommand = new StringJoiner(" ", "\"&", "\"")
                .add(String.format("'%s'", script.normalize().toString()));
        for (String param : params) {
            if (param.startsWith("-")) { // Its an option or switch
                innerCommand.add(param);
            } else {
                innerCommand.add(String.format("'%s'", param));
            }
        }
        StringJoiner command = new StringJoiner(" ")
                .add("powershell.exe")
                .add("-NoProfile")
                .add("-NoLogo")
                .add(innerCommand.toString());

        try {
            Process process = Runtime.getRuntime()
                    .exec(command);
            process.getOutputStream().close(); // Make sure CMD does not wait for further commands
            boolean exited = process.waitFor(COMMAND_TIMEOUT_VALUE, COMMAND_TIMEOUT_UNIT);
            String stdOutResult = new String(process.getInputStream().readAllBytes());
            T commandResult;
            if (exited) {
                if (process.exitValue() == 0) {
                    commandResult = onSuccess.apply(stdOutResult);
                } else {
                    String stdErrResult = new String(process.getErrorStream().readAllBytes());
                    commandResult = onFailure.apply(stdOutResult, stdErrResult);
                }
            } else {
                commandResult = onTimeout.get();
            }
            return commandResult;
        } catch (IOException | InterruptedException ex) {
            throw new SystemCommandFailedException(String.format("Processing %d errored", commandID), ex);
        }
    }

编辑: 附加 a[Console]::Out.Flush()并不能解决问题。

4

0 回答 0