【问题标题】:Zenity bash command not working with JavaZenity bash 命令不适用于 Java
【发布时间】:2015-11-23 19:15:41
【问题描述】:

我正在尝试使用 zenity 命令从用户那里获取输入。这是我传递给 zenity 的命令:

zenity --question --title "Share File" --text "Do you want to share file?"

这是使用 Java 执行命令的代码:

private String[] execute_command_shell(String command)
{
    System.out.println("Command: "+command);
    StringBuffer op = new StringBuffer();
    String out[] = new String[2];
    Process process;
    try
    {
        process = Runtime.getRuntime().exec(command);
        process.waitFor();
        int exitStatus = process.exitValue();
        out[0] = ""+exitStatus;
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line = "";
        while ((line = reader.readLine()) != null)
        {
            op.append(line + "\n");
        }
        out[1] = op.toString();
    }
    catch (Exception e)
    {
        e.printStackTrace();
    }

    return out;
}

虽然我得到一个输出对话框,但标题只有第一个单词“Share”,问题的文本也只显示一个单词“Do”

对这种奇怪的行为有什么解释吗?有什么解决办法?

【问题讨论】:

  • 命令字符串变量中的引号正确吗?
  • @EtanReisner 上面提到的zenity命令是execute_command_shell方法第一行的输出
  • 那你把Command: 去掉了吗?行。听起来有些东西通常不会将命令解析为shell命令。 WillShackleford 的答案涵盖(虽然很尴尬)使用一组参数。这可能是最好的答案。
  • 是的,这对我有用。但这让我想知道 Runtime 类是如何实现的,直接字符串命令出了什么问题。
  • 据推测,正如 WillShackleford 也提出的那样,Runtime 没有使用 shell,而是在解析字符串本身(而不是使用 shell 引用规则)。大概这也记录在某个地方的类文档中。

标签: java bash zenity


【解决方案1】:

这对我有用:

Runtime.getRuntime().exec(new String[]{"zenity","--question","--title","Share File","--text","Do you want to share file?"})

我建议在 java 代码中拆分参数,以便您可以检查而不是用引号传递整个命令。

这里是一个例子,包括处理引号的拆分:

String str = "zenity --question --title \"Share File\" --text \"Do you want to share file?\"";
String quote_unquote[] = str.split("\"");
System.out.println("quote_unquote = " + Arrays.toString(quote_unquote));
List<String> l = new ArrayList<>();
for(int i =0; i < quote_unquote.length; i++) {
    if(i%2 ==0) {
        l.addAll(Arrays.asList(quote_unquote[i].split("[ ]+")));
    }else {
        l.add(quote_unquote[i]);
    }
}
String cmdarray[] = l.toArray(new String[l.size()]);
System.out.println("cmdarray = " + Arrays.toString(cmdarray));
Runtime.getRuntime().exec(cmdarray);

【讨论】:

  • 将命令拆分为参数数组对我有用 :) 但是你能解释一下为什么会这样吗?
  • 我不确定我自己是否理解这些细节。但是据我所知,当您运行 shell 时,shell 会拆分参数处理引用的块等,而 zeniity 程序会获取已经拆分的参数。在这里,我们绕过 shell 并将命令更直接地传递给操作系统,它不会像 shell 那样处理引号。
【解决方案2】:

您也可以使用UiBooster for Java 创建此对话框。这样你就不必安装zenity,你也不局限于windows上的linux或gtk。

String userInput = new UiBooster().showTextInputDialog("Do you want to share file?");

【讨论】:

    猜你喜欢
    • 2016-07-17
    • 2023-03-22
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 2022-01-11
    • 2016-09-07
    • 1970-01-01
    相关资源
    最近更新 更多