I want to run some unix/shell commands in Java and process the output. I used getRuntime.exec(), but it is not giving correct output for some commands like ls directory_path/*.tar.gz . For that command my program is not giving any output but it is giving error saying No such file or directory. But the same command is giving correct output on command prompt.
Is there any other way to execute commands which include wildcards in Java?
Yes there is.
You have three potential problems in your code:
Assuming you want to see the output of the external command you need to take care of the output it produces, and print it yourself.
Follow the example I’ve provided over here:
The shell expansion of
*doesn’t work if you naively go throughRuntime.exec.You have to go through/bin/bashexplicitly.If you try to list the content of
directory_path/*.tar.gzyou should know that (if you’re not starting with a/)directory_pathwill be resolved relative to the current working directory. Try at first to give the absolute path to make sure it works, and then try to figure out why it can’t find the relative path.Here’s a complete example that should work: