Pages

Tuesday, 10 November 2020

Run CMD In Background

How To Run Command Prompt In Background By Java Code?

Follow the instructions:

  • First take a ProcessBuilder object with parameters("cmd.exe","/c","assoc")
    • Put required command instead of "assoc".
  • Give directory name (System.getProperty("user.dir")).
  • Defining true to redirectErrorStream() is recommended
  • Now call start method via ProcessBuilder object.

    Following code can be used to run cmd in backgound and read/print output.

public class Main {
	public static void main(String[] args) throws IOException {
		ArrayList<String> output =  new ArrayList<String>();
		boolean executionStatus=false;
		
		String myDirectory = System.getProperty("user.dir"); 	
		try {
			ProcessBuilder pbuilder = new ProcessBuilder("cmd.exe","/c","assoc");
			pbuilder.directory(new File(myDirectory));
			pbuilder.redirectErrorStream(true);
			Process process = pbuilder.start();
            
		//Reading Output
			BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
			String line;
			while(true) {
				line = reader.readLine();
				if(line==null)break;
				output.add(line);			
			}
			executionStatus = true;
		} catch (Exception e) {
			e.printStackTrace();
			executionStatus = false;
		}
        
		System.out.println("executionStatus : "+executionStatus);
		System.out.println("output:");
		for(String x:output)
			System.out.println(x);
	}
}

For running Command Prompt directly but not in background, Following code can be used:
Runtime.getRuntime().exec(new String[] {"cmd", "/K", "Start"});

No comments:

Post a Comment

Deploy Your Code To Heroku App

GitHub To Heroku Node.js To Heroku  1. HOW TO DEPLOY AN APP TO HEROKU FROM GITHUB