javabashzenity

Zenity bash command not working with Java


I'm trying to take input from the user using the zenity command. Here's the command I'm passing to zenity :

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

Here's the code using Java to execute the command :

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

Although I'm getting an output dialog box, the title has only the first word "Share" and the text of the question also displays only one word "Do"

Is there any explanation to this weird behavior? What's the work around ?


Solution

  • This worked for me:

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

    I would recommend splitting the arguments in the java code so that you can check rather than passing the whole command with quotes.

    Here is an example including the splitting to handle quotes:

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