Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Using unix commands in java

 
jagan raja
Ranch Hand
Posts: 54
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Rancher
Posts: 42967
73
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The working directory is most likely not what you expected it to be - you should use absolute paths.
 
Rob Spoor
Sheriff
Pie
Posts: 20527
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic