从 Groovy/Java 调用外部进程给出了意外的结果

Calling external process from Groovy/Java gives unexpected result

从 Groovy/Java 我尝试执行以下命令:cmd /c echo mytext.

import java.nio.charset.Charset

println(Charset.defaultCharset().displayName()) //returns windows-1250
//in console chcp returns 852

def arg = "/c echo mytext"
def pb = new ProcessBuilder("cmd", arg)
def proc = pb.start()

def stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream(), "CP852"))
def stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream(), "CP852"))

def line = null
println("Here is the standard output of: cmd " + arg)
while ((line = stdInput.readLine()) != null) {
    println(line)
}

println("Here is the standard error of the command (if any):")
while ((line = stdError.readLine()) != null) {
    println(line)
}

Groovy: 2.4.21, 3.0.9

Java: zulu11.50.19-ca-fx-jdk11.0.12-win_x64

结果为mytext"(包括结束双引号)。我不明白为什么会有双引号。谁能帮我解释一下为什么会在那里?

谢谢。

简而言之:ProcessBuilder 会将每个包含空格的参数用双引号括起来

所以,ProcessBuilder("cmd", "/c echo mytext") 实际上运行 cmd "/c echo mytext"

在命令提示符下尝试这个命令:

c:\> cmd "/c echo mytext"
mytext"

^^^ 这正是您的结果

为什么 cmd 以这种方式解释参数的问题必须向微软提出 - 也许有一个合乎逻辑的解释

但是 echo 不解析参数并按原样输出参数行

c:\> echo "my text"
"my text"

c:\> echo my text
my text

表示echo my text的正确答案:ProcessBuilder("cmd", "/c", "echo my text")


让我为您的代码建议一个 groovy 变体:

def out = {s-> print(s)} as Appendable
def err = {s-> print(s)} as Appendable

def command = ['cmd', '/c', 'echo my text']
def proc = command.execute()

proc.waitForProcessOutput(out,err)