Zenity bash命令不适用于Java

Zenity bash命令不适用于Java,java,bash,zenity,Java,Bash,Zenity,我正在尝试使用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); StringBu

我正在尝试使用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);
String str=“zenity--question--title\'Share File\”--text\'you want Share File?\”;
字符串quote\u unquote[]=str.split(“\”);
System.out.println(“quote_unquote=“+Arrays.toString(quote_unquote));
列表l=新的ArrayList();
对于(int i=0;i
或者,您可以使用Java来创建此对话框。这样,您就不必安装zenity,也不局限于windows上的linux或gtk

String userInput=new UiBooster().showTextInputDialog(“是否要共享文件?”);

command string变量中的引号是否正确?@EtanReisner顶部提到的zenity命令是execute\u command\u shell方法的第一行的输出,然后您将
command:
从中剥离出来?好。听起来好像有什么东西没有正常地将该命令解析为shell命令。WillShacklef给出了答案作战需求文件封面(虽然笨拙)改为使用参数数组。这可能是最好的答案。是的,这对我来说很有效。但这让我想知道运行时类是如何实现的,以及直接字符串命令出了什么问题。据推测,正如WillShackleford也假设的那样,
运行时
没有使用shell,而是在解析字符串本身(并且不使用shell引用规则)。大概这也记录在类文档的某个地方。将命令拆分为参数数组对我来说很有用:)但是你能解释一下为什么会发生这种情况吗?我不确定我自己是否理解细节。但正如我所理解的,当你运行一个shell时,shell会拆分参数,处理带引号的块等,zeniity程序会得到已经拆分的参数。这里我们绕过shell,将命令更直接地传递给操作系统tem不会像shell那样处理引号。