I am writing a java program that takes command and run it in unix shell. I have managed to get the output, but I need the program to detect if the given command is invalid, now, if I put in an invalid command, it gives me an error. Otherwise, it's working fine. Can anybody help me with this?? Here is my code:
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();
}
}
Stringequality with==or!=. You should be using something like!sentence.equals(" ")and!sentence.equals("exit")echo foo baris ok butecho 'foois not?