开发者

How does java execute terminal commands?

Found this to be tricky; Having the following code:

String cmd = "find /home/folder/ -type f"; 
Runtime run = Runtime.getRuntime() ; 
Process pr = run.exec(cmd); 
pr.waitFor();

I'll pr.getInputStream() and have the proper find result there, no problem. However, if I want to be a bit more specific and have my command as cmd = "find /home/folder/ -type f -name somefile*";, the input stream will be empty.

Now, I thought it would be something related to the string expansions done by the interactive shell (which wouldn't be used in this case, I suppose). In this case the * would have no meaning, and find would be looking for files really named "*" (something like \*). So I've tried to have my command as sh -c "find /ho开发者_StackOverflow社区me/folder/ -type f -name somefile*". But it didn't work either...

What am I missing?

thanks,

f.

Ps.: It is an AIX box, with IBM's Java JVM.


I always escape the wildcard when using find:

cmd = "find /home/folder/ -type f -name somefile\\*";


I think it would be better if you use ProcessBuilder or maybe Runtime.exec methods as they don't need shell escaping and don't run through the shell.

  • ProcessBuilder, is loads more flexible
  • Runtime.exec, differs from the form that takes only a String
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜