title: how to validate unix command with java
body: <p>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:</p>
  
  <pre><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("&gt; ");
                   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();
      }
  
  }
  </code></pre>