Solved

Java RunTime exec method's Usage

Posted on 2009-07-14
15
578 Views
Last Modified: 2012-05-07
Hi; I try to use run following script by Runtime.getRuntime.exec. But I do not know how to write arguments.

String[] cmdArray = new String[]{"ps","awk","sort","uniq","awk","grep"};
String[] parameters = new String[]{"aux", "'{print $4 \"\\t\"$11}'"....",null,"-c","'{print $2\" \"$1\" \"$3}'","java"};
       
Process proc = Runtime.getRuntime.exect(cmdArray,parameters);

Am I right?

ps aux | awk '{print $4"\t"$11}' | sort | uniq -c | awk '{print $2" "$1" "$3}' | grep java
0
Comment
Question by:JianJunShen
  • 7
  • 4
  • 2
  • +1
15 Comments
 
LVL 20

Expert Comment

by:a_b
ID: 24850670
What is the error/issue that occurs when you run this? looks okay to me.
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 150 total points
ID: 24850675
With a command as complex as that, you would be much better advised to put it in a shell script and Runtime.exec that

But see

http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 150 total points
ID: 24850700
That would be


String[] args = { "/bin/bash", "x.sh" };
Process p = Runtime.getRuntime().exec(args);

Open in new window

0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

Author Comment

by:JianJunShen
ID: 24851464
where shall I put script file(x.sh)?

String[] args = { "/bin/bash", "x.sh" };
Process p = Runtime.getRuntime().exec(args);
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24851509
Well a safe place would be in your home directory
0
 

Author Comment

by:JianJunShen
ID: 24857276
well, if one use eclipse, it is better to put in project root directory. Pararel to src folder.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24857313
:-)

btw, my comment at http:#24850675 is devoted to getting output
0
 
LVL 2

Accepted Solution

by:
nkiggs earned 350 total points
ID: 24867139
Hi,

To run complex commands you can simulate your multiple command line arguments with a bufferedwriter writing to the shell you create. So you will have all the commands like:

/bin/sh
cd ..
pwd
exit

to create a shell(or you can use /bin/csh) go one directory backwards(cd ..) and then finally print the working directory (pwd) and finally exit (exit) after reading with the bufferedreader output from pwd command. Code example below to do this. Alter to suite the order you would type your commands in your shell script.
  	public int runProcess(){
      	// code to commence processing		
		String line;
		File wd = new File("/bin");	//location of sh executable 
		Process proc = null; 
		
		try { 
			proc = Runtime.getRuntime().exec("/bin/sh", null, wd); 
		} 
		catch (IOException e) { 
			e.printStackTrace(); 
		} 
		
		if (proc != null) { 
			BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream())); 
			PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true); 
			out.println("cd ..");	
			out.println("pwd");				
			out.println("exit"); 
			try { 	
				int x = 0;
				while ((line = in.readLine()) != null) { 
					if (x > -1){
						System.out.println(line + "\n");
					}
					x++;				
				} 
				proc.waitFor(); 
				in.close(); 
				out.close(); 
				proc.destroy(); 
			} 
			catch (Exception e) { 
				e.printStackTrace(); 
			} 
		}      		
   	}

Open in new window

0
 
LVL 2

Expert Comment

by:nkiggs
ID: 24867188
Hi,

You can simulate all the commands you will normally enter into your shell script window by using both BufferedReader and BufferedWriter simultaneously. Therefore, your application would operate as if you are entering commands manually (BufferedWriter) and get all the output as you enter commands (BufferedReader).

This output can be manipulated with a variable x that tracks the number of lines outputed and you can use this output by manipulating the string "line".

See my comment on the question.

Regards,

nkiggs
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24874504
nkiggs probably didn't intend to object i'd guess
0
 

Author Comment

by:JianJunShen
ID: 24874618
I think ID:24867139 is the best solution.       ID:24850700 is assistant answer. It is also a good one.
0
 

Author Closing Comment

by:JianJunShen
ID: 31603292
Experts answer are excellent.
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24874652
The late addition is only appropriate when you for some reason want to run an interactive shell from within Java, which was certainly not mentioned as a requirement...
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 24874657
*Is* it a requirement JianJunShen?
0

Featured Post

Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
firstswap challenge 20 77
eclipse buid path vs tomcat lib path 10 23
by zero exception 10 40
What's wrong with this code? 4 23
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Java functions are among the best things for programmers to work with as Java sites can be very easy to read and prepare. Java especially simplifies many processes in the coding industry as it helps integrate many forms of technology and different d…
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question