Zenity bash 命令不适用于 Java

Zenity bash command not working with Java

我正在尝试使用 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"

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

这对我有用:

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);

或者,您可以使用 UiBooster 或 Java 创建此对话框。这样你就不必安装 zenity 并且你不限于 linux 或 windows.

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