【发布时间】:2014-10-08 03:16:09
【问题描述】:
我正在编写一个 java 程序,它接受命令并在 unix shell 中运行它。我设法得到了输出,但是我需要程序来检测给定的命令是否无效,现在,如果我输入一个无效的命令,它会给我一个错误。否则,它工作正常。有人可以帮我吗?这是我的代码:
public class TestCommand {
public static void main(String[] args) {
TestCommand obj = new TestCommand();
String sentence ="";
Scanner scn = new Scanner(System.in);
while (sentence != " ")
{
if (sentence !="exit")
{
System.out.println("> ");
sentence = scn.nextLine();
String outPut = obj.executeCommand(sentence);
System.out.println(outPut + "\n");
}
else
{
System.exit(2);
}
}
}
private String executeCommand(String sentence)
{
StringBuffer output = new StringBuffer();
Process p;
try
{
p = Runtime.getRuntime().exec(sentence);
p.waitFor();
BufferedReader bfrd = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = bfrd.readLine())!= null)
{
output.append(line);
}
bfrd.close();
}
catch (Exception e) {
e.printStackTrace();
}
return output.toString();
}
}
【问题讨论】:
-
不是直接点,但不要测试
String与==或!=是否相等。你应该使用类似!sentence.equals(" ")和!sentence.equals("exit") -
感谢您的建议 :) 我会更改它...
-
您正在尝试确定给您的 shell 命令是否是语法上有效的 shell 命令?所以
echo foo bar可以,但echo 'foo不行? -
尝试检查exitValue? docs.oracle.com/javase/7/docs/api/java/lang/…