【发布时间】: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 引用规则)。大概这也记录在某个地方的类文档中。