5

If for example I chose to run a bash script that would output (echo) the time e.g. CheckDate.sh. How could I run this from Java and then print the result of the bash script (the date) in my Java program?

skaffman
  • 398,947
  • 96
  • 818
  • 769
Mike
  • 2,266
  • 10
  • 29
  • 37
  • Take a look at another question similar to yours: http://stackoverflow.com/questions/2875085/execute-external-program-from-java –  Feb 03 '12 at 09:12

3 Answers3

6

Try this code.

String result = null;
try {
    Runtime r = Runtime.getRuntime();                    

    Process p = r.exec("example.bat");

    BufferedReader in =
        new BufferedReader(new InputStreamReader(p.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null) {
        System.out.println(inputLine);
        result += inputLine;
    }
    in.close();

} catch (IOException e) {
    System.out.println(e);
}
Sunil Kumar B M
  • 2,735
  • 1
  • 24
  • 31
3

One way would be to assign your script execution in a Process object and retrieve the script ouput from its inputstream.

try {
    // Execute command
    String command = "ls";
    Process process = Runtime.getRuntime().exec(command);

    // Get the input stream and read from it
    InputStream in = process.getInputStream();
    int c;
    while ((c = in.read()) != -1) {
        process((char)c);
    }
    in.close();
} catch (IOException e) {
    LOGGER.error("Exception encountered", e);
}

Another way would be to make your bash scripts write its output in a file and then read this file back from Java.

Good luck.

bugske
  • 218
  • 1
  • 8
2

The java.lang.Process class is intended for such purposes. You run an external process in Java either using the (simpler) java.lang.Runtime.exec function, or the (more complex) java.lang.ProcessBuilder class. Both give you, in the end, an instance of said java.lang.Process, whose getInputStream method you can call to get a stream from which you can read its output.

See the Javadoc for more information.

Dolda2000
  • 25,216
  • 4
  • 51
  • 92