Solved

calling system commands within Java

Posted on 2011-03-16
21
320 Views
Last Modified: 2012-06-22
Hi,
Can we directly call a system command within java code?

Here is an example:

grep '^(SdD)' args[2]; 

Open in new window


args[2] is the path to a text file.

Thanks,

0
Comment
Question by:Tolgar
  • 10
  • 7
  • 4
21 Comments
 
LVL 47

Expert Comment

by:for_yan
ID: 35151445
Yes we can - you should use

Runtime.getRuntime().exec("command arguments");
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35151470
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35151480

And this is how you read the ouput from the second example (importnat part of the process):
http://www.exampledepot.com/egs/java.lang/ReadFromCommand.html
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35151504
You'd be better off calling a shell script. But see my comments here http:Q__26889988.html
Process p = Runtime.getRuntime().exec(new String[] { "sh mygrep.sh", args[2] });

Open in new window

0
 

Author Comment

by:Tolgar
ID: 35151736
So as a result is this correct?

java.lang.String myFiles = Runtime.getRuntime().exec(grep '^(SdD)' args[3]);

Open in new window



Thanks,
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35151787
Sorry that should have been
Process p = Runtime.getRuntime().exec(new String[] { "sh", "mygrep.sh", args[2] });

Open in new window

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35151813
With a shell script consisting of

grep '^(SdD)' "${@}"

I've just tested the following code and it works fine.

You can grep in files in pure Java too
public class GrepTest {
    public static void main(String[] args) throws Exception {
	Process p = Runtime.getRuntime().exec(new String[] { "sh",  "mygrep.sh", args[2] });

	StringBuilder stderr = new StringBuilder();
	StringBuilder stdout = new StringBuilder();
	net.proteanit.io.IOUtils.collectProcessStreams(p, stderr, stdout);
	System.out.println(stdout);
    }
}

Open in new window

0
 

Author Comment

by:Tolgar
ID: 35151893
So is this gonna work?

java.lang.String myFiles = Runtime.getRuntime().exec(grep '^(SdD)' args[3]);

Open in new window



Thanks,
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35152037
No, one thing
you need to havwe arguments in quotes:

Process p = Runtime.getRuntime().exec("grep '^(SdD)'  " + args[3]);
and then you need to collect the output as CEHJ showed:

      StringBuilder stderr = new StringBuilder();
      StringBuilder stdout = new StringBuilder();
      net.proteanit.io.IOUtils.collectProcessStreams(p, stderr, stdout);
      System.out.println(stdout);

0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35152045
Let's take a closer look there: i don't know what version of grep you're using, but the effect of that command with the greps i know would effectively either return args[3] or nothing. What is your intention there?
0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 

Author Comment

by:Tolgar
ID: 35152134
So args[3] is a path to a file. What I would like to do is:

grep the lines in this file that starts with s or d or D.

Thanks,
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35152151
That would be
grep '^[sdD]' foo

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35152176
Maybe it is still easier to do it in Java, rather than going to the system ?
0
 

Author Comment

by:Tolgar
ID: 35152251
You may be right. So how can I make it in Java only without going to the system?

Thanks,
0
 
LVL 86

Expert Comment

by:CEHJ
ID: 35152263
Just read into a List and add if

s.matches("^[sDd].*");
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35152272


DataInputStream in = new DataInputStream(new FileInputStream(args[3]))
String buff = null;
while((buff=in.readLine() )!= null){
buff = in.readLine();
if(buff.startsWith("s") || buff.startsWith("S") || buff.startsWith("D")){
System.out.println(buff);
}
in.close();
}
0
 
LVL 47

Accepted Solution

by:
for_yan earned 200 total points
ID: 35152294

Or you can collect it to the String like that:

String s = "";
try{
DataInputStream in = new DataInputStream(new FileInputStream(args[3]))
String buff = null;
while((buff=in.readLine() )!= null){
buff = in.readLine();
if(buff.startsWith("s") || buff.startsWith("S") || buff.startsWith("D")){
System.out.println(buff);
s += buff + System.getProperty("line.separator");
}

}
in.close();
} catch(Exception ex){
ex.printStackTrace();
}
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35152303
I guess in the first case I missed one closing brace;
in the second case should be OK
0
 
LVL 86

Assisted Solution

by:CEHJ
CEHJ earned 50 total points
ID: 35152321
Try the following (the superclass is at http://technojeeves.com/joomla/index.php/free/74-string-list ) and try it out with a file called 'x.txt'
public class SelectiveStringList extends StringList {

    @Override
    public boolean add(String s) {
	boolean result = s.matches("^[sDd].*");
	if (result) {
	    super.add(s);
	}
	return result;
    }
    public static void main(String[] args) {
	SelectiveStringList matches = new SelectiveStringList();
	matches.read("x.txt");
	for(String s :  matches) {
	    System.out.println(s);
	}
    }
}

Open in new window

0
 
LVL 47

Expert Comment

by:for_yan
ID: 35152360
Sorry one readline() too much in my code
0
 
LVL 47

Expert Comment

by:for_yan
ID: 35152365
Just remobve first line inside the while loop
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
topping2 challenge 13 82
Java SE 8u111  Lot of stuff broke 11 54
couple of eclipse 5 23
Oracle SQL syntax check  without executing 6 36
After being asked a question last year, I went into one of my moods where I did some research and code just for the fun and learning of it all.  Subsequently, from this journey, I put together this article on "Range Searching Using Visual Basic.NET …
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

910 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

Need Help in Real-Time?

Connect with top rated Experts

24 Experts available now in Live!

Get 1:1 Help Now