【问题标题】:Calling external process from Groovy/Java gives unexpected result从 Groovy/Java 调用外部进程会产生意想不到的结果
【发布时间】:2021-09-18 22:35:31
【问题描述】:

从 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("cmd", "/c", "echo", "mytext") 应该有帮助。
  • @daggett 谢谢,它有效。如此简单,它并没有发生在我身上。而且我仍然对造成双重问题的原因感到好奇。你知道它为什么在那里吗?
  • “我仍然对造成双引号的原因感到好奇。你知道它为什么会出现吗?” - 在代码ProcessBuilder("cmd", "/c", "echo", "mytext") 中,您可以将双引号替换为单引号并具有完全相同的行为。

标签: java groovy process external


【解决方案1】:

简而言之: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)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-20
    • 2019-04-05
    • 1970-01-01
    • 2023-03-02
    • 2021-03-10
    • 2019-04-07
    相关资源
    最近更新 更多