wood burning stoves*
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
Author

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
Marshal

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


Ping & DNS - my free Android networking tools app
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19653
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
Don't get me started about those stupid light bulbs.
 
subject: Using unix commands in java
 
Similar Threads
Problem in process
Help with runtime.exe and javac from command line
executing linux commands through java socket
How to connect to Linux using Java code?
Runtime.getRuntime( ).exec( command ); Win vs Unix