Reputation: 35
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?
Upvotes: 2
Views: 3525
Reputation: 421080
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 through Runtime.exec
.You have to go through /bin/bash
explicitly.
If you try to list the content of directory_path/*.tar.gz
you should know that (if you're not starting with a /
) directory_path
will 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:
Process proc = new ProcessBuilder("/bin/bash", "-c",
"ls /.../directory_path/*.tar.gz").start();
Reader reader = new InputStreamReader(proc.getInputStream());
int ch;
while ((ch = reader.read()) != -1)
System.out.print((char) ch);
reader.close();
Upvotes: 6
Reputation: 15046
"ls directory_path/*.tar.gz" works relative to CURRENT directory.
Upvotes: 0
Reputation: 68877
That is because you specified a relative path to the directory and your application is running in a working directory. The path you specified is relative to that working directory.
To find out what the absolute path is, you can check out the working directory.
System.out.println("Working directory: " + System.getProperty("user.dir"));
Upvotes: 0