woensdag 13 april 2011

[Java] Execute a terminal-command in Java

Here's an easy way to implement command calls in Java. The program prints the response from the CLI.


import java.io.*;
  1. public class TestExec {
  2. public static void main(String[] args) {
  3. try {
  4. Process p = Runtime.getRuntime().exec("cmd /C dir");
  5. BufferedReader in = new BufferedReader(
  6. new InputStreamReader(p.getInputStream()));
  7. String line = null;
  8. while ((line = in.readLine()) != null) {
  9. System.out.println(line);
  10. }
  11. } catch (IOException e) {
  12. e.printStackTrace();
  13. }
  14. }
  15. }

Qkyrie

1 opmerking:

  1. To get easy control over the environment of your subprocess(e.g. working dir), you can use ProcessBuilder.

    BeantwoordenVerwijderen