Run Windows script from Java code – Java run script example

Today we are going to show you how to start a script and read its output in a Java program. We are going to run a windows batch file in our example but you can run a script from Linux or any UNIX system with this code as well.

test.bat

Our sample script displays text. It looks like this:

@echo off
echo.
echo.
echo *****************************************************
echo * For more great tutorials visit us at itcuties.com *
echo *****************************************************
echo.
echo.

When you run this script you will get the following output:


*****************************************************
* For more great tutorials visit us at itcuties.com *
*****************************************************

Java run script code

Here is our solution. This program starts a process in which a script is being run. Next we are reading the running process output.

package com.itcuties.java;

import java.io.IOException;
import java.io.InputStream;

/**
* This code runs the script
*
* @author itcuties
*
*/
public class RunScript {

   public static void main(String[] args) {
       try {
           // Run the process
           Process p = Runtime.getRuntime().exec("cmd /c scripts\\test.bat");
           // Get the input stream
           InputStream is = p.getInputStream();

           // Read script execution results
           int i = 0;
           StringBuffer sb = new StringBuffer();
           while ( (i = is.read()) != -1)
               sb.append((char)i);

           System.out.println(sb.toString());

       } catch (IOException e) {
           e.printStackTrace();
       }

   }

}

Running this code results in a following output:

*****************************************************
* For more great tutorials visit us at itcuties.com *
*****************************************************

Download this sample code here.

This code is available on our GitHub repository as well.

One Response to "Run Windows script from Java code – Java run script example"

  1. narendra says:

    wer we have store that bat. file

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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


*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>