Jump to content



Photo

[Java] Print output of shell command


  • Please log in to reply
No replies to this topic

#1 Sikh

Sikh

    Neowin Addict!

  • Tech Issues Solved: 2
  • Joined: 11-March 07
  • Location: localhost
  • OS: Windows 7 / 10.8 / Ubuntu Server
  • Phone: Nexus 5 PA 4.4.2 / iPhone 5

Posted 03 February 2013 - 03:39

So Im working on a little project right now and currently im trying to run a shell command under java.

Everything works great, except I cant print the output of the shell command until its completely done executing. For this example / testing im using the rsync command in bash. How can I get java to print out whats happening in shell?
This code is running in its own method and in another thread so the ActionListener I add to the button that'll execute it wont hold it up. Its working like I expect except for it not printing right away. A lot of stuff online says to redraw / update, but i've done both to my Text Area and nothing.

Any ideas guys?

Code:
// Trial Code

   String shellcommand = new String("");
   shellcommand = "time rsync -Phav /Users/sikh/Downloads/ /Users/sikh/Desktop/Test";
  
   Runtime run = Runtime.getRuntime();
   Process cmdProcess = null;
  
   try {
	cmdProcess = run.exec(shellcommand);
	} catch (IOException e) {
	 e.printStackTrace();
	}
  
   try {
	cmdProcess.waitFor();
   } catch (InterruptedException e) {
	e.printStackTrace();
   }
  
   BufferedReader reader = new BufferedReader(new InputStreamReader(cmdProcess.getInputStream()));
   String line = "";
   try {
	while ((line = reader.readLine()) != null)
	{
	 mainclass.setText(line);
	} // end while
	} catch (IOException e) {
	 e.printStackTrace();
	} // end try

// End Trial Code





Click here to login or here to register to remove this ad, it's free!