File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Running UNIX command from Java

 
Donny Wi
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I'm having problem running the UNIX "grep" command from java.
This is what my code looks like:

When I ran the "grep" command above, it return exit code=1, which means no match found.
When I replace the "grep" command with "ls", it works fine. When I replace the "grep" command with "wc -l", first it returns zero but when I added a empty loop to delay the parent program, I got the right value.
I use waitFor() method, but I think it does not work well.
Can someone please help me or tell my why "grep" command does not work from Java?
 
William Barnes
Ranch Hand
Posts: 986
Eclipse IDE Firefox Browser Tomcat Server
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Ya, I get the same problem.
 
Donny Wi
Greenhorn
Posts: 13
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I found the answer but I can't explain why:
Instead of using
1. Runtime.getRuntime().exec(sCommand);
I use
2. Runtime.getRuntime().exec(new String[] {"/usr/bin/sh", "-c", sCommand});
I saw some example that runs multiple command by using code number 2, so I just experiment with the code and suddently the process.waitFor() will actually wait until the sub-process is complete. I don't know why.
So, there was my 10 hours of experiment with Runtime class in Java.
Donny
 
Cindy Glass
"The Hood"
Sheriff
Posts: 8521
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Just think how many OTHER people will not have to waste 10 hours discovering that - just because of YOU.
You should be pleased with yourself . WE are .
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic