File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes Using unix commands in java Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Using unix commands in java" Watch "Using unix commands in java" New topic

Using unix commands in java

jagan raja
Ranch Hand

Joined: Jan 29, 2010
Posts: 54
Hi All,

I am able to retrieve and store file in the unix box using java.(by importing com.jcraft.jsch package).

Now I need to pass unix commands (cat, grep) in java. How can i do that?

I read the forum and used the below code to search for success string in filename.log.

And I get the following error

Cannot run program "cat": CreateProcess error=2, The system cannot find the file specified
at java.lang.ProcessBuilder.start(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)
at java.lang.Runtime.exec(Unknown Source)

Can any one help me out?
Ulf Dittmer

Joined: Mar 22, 2005
Posts: 42965
The working directory is most likely not what you expected it to be - you should use absolute paths.
Rob Spoor

Joined: Oct 27, 2005
Posts: 20269

Also, "cat filename.log | grep success" is not one process. It's one process ("grep success") that is using the output of another process ("cat filename.log") as its input. This is handled by the shell (BASH, KSH, CSH etc) usually. When doing this in Java you need to do this yourself.

I see some options:
1) copy the contents of the input stream of the first process to the output stream of the second process, then read the input of the second process:

2) replace the catting with a Java input stream:

3) replace it all with Java code:
If the regex becomes a little more complex you can use java.util.regex.Pattern instead of the contains method.

Personally, I would go for option three. If you don't, read this first.

How To Ask Questions How To Answer Questions
I agree. Here's the link:
subject: Using unix commands in java
jQuery in Action, 3rd edition