java executing linux command

2019-04-12 07:52发布

I`m trying to execute linux commant 'cat' from java code, but it does not working.

Runtime.getRuntime().exec("cat /home/roman/logs/*");  

And it working well for cat of single file

Runtime.getRuntime().exec("cat /home/roman/logs/mylog.log");

My question is how to cat all files on some dir from java ?

3条回答
看我几分像从前
2楼-- · 2019-04-12 08:18

Runtim.exec() does not use a shell to execute the command. Therefore the wildcard is not expanded. Try the solution explained in Want to invoke a linux shell command from java

查看更多
在下西门庆
3楼-- · 2019-04-12 08:21

You could put all files under the dir into a collection and iterate over it:

File[] files = dir.listFiles();
for (File f : files) {
  Runtime.getRuntime().exec("cat "+dir.getAbsolutePath()+File.separator+f.getName());
}
查看更多
做自己的国王
4楼-- · 2019-04-12 08:28

You can't use * with the exec() command (you would need a shell). A solution could be to write a script and then exec() that script from your java application.

查看更多
登录 后发表回答