Executing batch file(.bat) from Java
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class JavaRunCommand { public static void main(String args[]) { String stream = null; try { Process p = Runtime.getRuntime().exec( "C:\WINDOWS\system32\cmd.exe /c start C:\Batch\test.bat"); BufferedReader stdInput=new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader stdError=new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command Input System.out.println("Standard output of the command:"); while ((stream = stdInput.readLine()) != null) { System.out.println(stream); } // read any errors from the attempted command System.out.println("Standard error of the command (if any):"); while ((stream = stdError.readLine()) != null) { System.out.println(stream); } System.out.println("ended!!"); } catch (IOException e) { System.out.println("Exception:"); System.err.println(e.getMessage()); } } }
|