Re: Spawn Shell Process

by treehousenorris2 » Fri Feb 05, 2021 8:43 pm

Got a shell to work from a plugin used with the SourceForge Sweet Home on Windows.

Code: Select all

runProcess("cmd /c echo hello world", true);
// or
// String cmdFilePath = runProcess("where cmd", true);
// String cmdToRun = cmdFilePath +" /c echo hello world";

private String runProcess(String command, boolean shouldWait) {
	    try {
	      Runtime rt = Runtime.getRuntime();
	      Process proc = rt.exec(command);
	      if (!shouldWait) {
	        return null;
	      }

	      System.out.println("--"+command);
	      InputStream stdout = proc.getInputStream();
	      InputStreamReader isrout = new InputStreamReader(stdout);
	      BufferedReader brout = new BufferedReader(isrout);
	      String output = "";
	      String lineout = null;
	      System.out.println("<OUT>");
	      while ( (lineout = brout.readLine()) != null) {
	        output += (output.length() == 0 ? "" : "\n") + lineout;
	        System.out.println(lineout);
	      }
	      System.out.println("</OUT>");
	  
	      InputStream stderr = proc.getErrorStream();
	      InputStreamReader isr = new InputStreamReader(stderr);
	      BufferedReader br = new BufferedReader(isr);
	      String line = null;
	      System.out.println("<ERROR>");
	      while ( (line = br.readLine()) != null) {
	        System.out.println(line);
	      }
	      System.out.println("</ERROR>");

	      int exitVal = proc.waitFor();
	      System.out.println("Process exitValue: " + exitVal);
	      return output;
	  
	    } catch (IOException ex) {
	      // TODO Auto-generated catch block
	      ex.printStackTrace();
	    } catch (InterruptedException ex) {
	      // TODO Auto-generated catch block
	      ex.printStackTrace();
	    }
	    return null;
	  }