How to execute native commands and external programs from Java

Many time we need to use native commands or other programs like Perl or Python scripts from Java. In this post let us explore how can we achieve this.

To explain we shall use simple ls command and print it’s output. We can execute external programs using Runtime class. Let’s see the code

The code is simple, let’s do a quick walk thru.

  • To execute any process we need a handle to Runtime class. This can be achieved by using Runtime.getRuntime() API
  • Next we use exec() API of the Runtime. This shall return a Process instance. We provide all the parameters to the exec() API
  • Process instance gives access to what is being written on the standard output, we wrap it as BufferedReader and prints the output.
  • Last we ensure to let the process complete.

The Process class also gives access to Error stream if needed. This can be useful in many situations.

There are other ways of doing this. ProcessBuilder is a class that help achieve the same functionality. We shall look at it in a different post.

Leave a Reply

Your email address will not be published. Required fields are marked *