Execute a system command – Rosetta Code.
Java
import java.util.Scanner; import java.io.*; public class Program { public static void main(String[] args) { try { Process p = Runtime.getRuntime().exec("cmd /C dir");//Windows command, use "ls -oa" for UNIX Scanner sc = new Scanner(p.getInputStream()); while (sc.hasNext()) System.out.println(sc.nextLine()); } catch (IOException e) { System.out.println(e.getMessage()); } } }
There are two ways to run system commands. The simple way, which will hang the JVM (I would be interested in some kind of reason). — this happens because the the inputStream buffer fills up and blocks until it gets read. Moving your .waitFor after reading the InputStream would fix your issue (as long as your error stream doesn’t fill up)
import java.io.IOException; import java.io.InputStream; public class MainEntry { public static void main(String[] args) { executeCmd("ls -oa"); } private static void executeCmd(String string) { InputStream pipedOut = null; try { Process aProcess = Runtime.getRuntime().exec(string); aProcess.waitFor(); pipedOut = aProcess.getInputStream(); byte buffer[] = new byte[2048]; int read = pipedOut.read(buffer); // Replace following code with your intends processing tools while(read >= 0) { System.out.write(buffer, 0, read); read = pipedOut.read(buffer); } } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException ie) { ie.printStackTrace(); } finally { if(pipedOut != null) { try { pipedOut.close(); } catch (IOException e) { } } } } }
And the right way, which uses threading to read the InputStream given by the process.
import java.io.IOException; import java.io.InputStream; public class MainEntry { public static void main(String[] args) { // the command to execute executeCmd("ls -oa"); } private static void executeCmd(String string) { InputStream pipedOut = null; try { Process aProcess = Runtime.getRuntime().exec(string); // These two thread shall stop by themself when the process end Thread pipeThread = new Thread(new StreamGobber(aProcess.getInputStream())); Thread errorThread = new Thread(new StreamGobber(aProcess.getErrorStream())); pipeThread.start(); errorThread.start(); aProcess.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException ie) { ie.printStackTrace(); } } } //Replace the following thread with your intends reader class StreamGobber implements Runnable { private InputStream Pipe; public StreamGobber(InputStream pipe) { if(pipe == null) { throw new NullPointerException("bad pipe"); } Pipe = pipe; } public void run() { try { byte buffer[] = new byte[2048]; int read = Pipe.read(buffer); while(read >= 0) { System.out.write(buffer, 0, read); read = Pipe.read(buffer); } } catch (IOException e) { e.printStackTrace(); } finally { if(Pipe != null) { try { Pipe.close(); } catch (IOException e) { } } } } }