How to Run Windows Commands in Java and Store Their Output in Log File

In our day to day work we need to run windows commands and verify their output. In order to automate these frequently used commands, we normally write them in batch file but this option does not produce log like file and does not have good file formatting features.To solve this problem, below given utility program can serve just the right purpose.

Here we make use of java.io class to write output file and make use of java's Runtime class methods to execute windows commands.

Below is the code, that will run windows commands and store their output in a .txt file with formatting and date of run of commands. Complete code is available at my GitHub Project to change it to suite your needs.


import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Arrays;
import java.util.Date;

public class RunningWinCmd {

   public static void main(String[] args) {
      String[] cmd = { "cmd.exe", "/c", "dir" }, cmd1 = { "hostname" };
      Process p, p1;
      try {
      // output file to write output of commands
      File outFile = new File("CmdOutput.txt");
      // "true" makes contents to get appended to output file
      FileWriter fw = new FileWriter(outFile, true); 
      BufferedWriter bw = new BufferedWriter(fw);
      // run cmd
      p = Runtime.getRuntime().exec(cmd);
      BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

      // calling class's static methods to write to output file
      writeDateToOutFile(bw);
      writeCmdToFile(cmd, bw);
      formatOutFile(bw);
      writeToOutFile(input, bw);
      formatOutFile(bw);
      
      input.close();
      p1 = Runtime.getRuntime().exec(cmd1);
      BufferedReader in = new BufferedReader(new InputStreamReader(p1.getInputStream()));

      writeCmdToFile(cmd1, bw);
      formatOutFile(bw);
      writeToOutFile(in, bw);
      formatOutFile(bw);

      bw.flush();
      bw.close();
      in.close();
      } catch (IOException e) {
        e.printStackTrace();
      }
}

public static void writeToOutFile(BufferedReader inObj, BufferedWriter outObj) {
   String temp = "";
   try {
      while ((temp = inObj.readLine()) != null) {
      outObj.write(temp);
      outObj.newLine();
      }
   } catch (IOException e) {
     e.printStackTrace();
     }
}

public static void formatOutFile(BufferedWriter outObj) {
   try {
   outObj.newLine();
   outObj.write("===========<cmd output>==============");
   outObj.newLine();
   } catch (IOException e) {
     e.printStackTrace();
     }
}

public static void writeDateToOutFile(BufferedWriter outObj) {
   Date date = new Date();
   try {
      outObj.newLine();
      outObj.write(date.toString());
      outObj.newLine();
   } catch (IOException e) {
      e.printStackTrace();
      }
}

public static void writeCmdToFile(String[] cmd, BufferedWriter outObj) {
   try {
   outObj.newLine();
   outObj.write(Arrays.toString(cmd)); // writes name of command to outFile
   outObj.newLine();
   } catch (IOException e) {
     e.printStackTrace();
     }
   }
}

Script Code Explanation:

Below code opens the output text file in append mode so that on each run of the script, the output of previous windows commands will not get lost. Here we call different constructor of FileWriter class that accepts File object and boolean value. When we set the boolean value to true, that means that the contents that will get written to the file that is represented by the File object should be appended and not over written.


FileWriter fw = new FileWriter(outFile, true); 

Below code gives us ability to run windows command and get its output.

p = Runtime.getRuntime().exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));

After this, we make series of calls to the methods written to provide formatting to the output file as well writing output of windows command to the output text file. These methods make code modular and reusable.

writeDateToOutFile(bw);
writeCmdToFile(cmd, bw);
formatOutFile(bw);
writeToOutFile(input, bw);
formatOutFile(bw);

Lets see the important method out of all methods, writeToOutFile() method accepts two arguments, one - inObj, which will have output of windows cmd and other argument - outObj, will have output text file's writer class object. Rest of the code is self-explanatory.

public static void writeToOutFile(BufferedReader inObj, BufferedWriter outObj) {
   String temp = "";
   try {
      while ((temp = inObj.readLine()) != null) {
      outObj.write(temp);
      outObj.newLine();
      }
   } catch (IOException e) {
     e.printStackTrace();
     }
}

In same line, we can make use of java.io class to copy contents one file to another file, the code for this can be found here.

Thats all folks!!
Don't forget to put comment about your doubts/questions/feedback!

Enjoy and Happy Testing!!


Comments

Popular posts from this blog

Simple Data Driven Framework script

Reading and writting data from .xlsx spreadsheet using Apache POI API

Generalized Apache POI script for reading and writing to .xlsx files