java执行linux命令

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9993873/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 05:35:01  来源:igfitidea点击:

java executing linux command

javalinuxbashcat

提问by Roman Iuvshin

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

我正在尝试从 java 代码执行 linux 命令“cat”,但它不起作用。

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 ?

我的问题是如何从 java 中抓取某个目录上的所有文件?

采纳答案by Yuval

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());
}

回答by talnicolas

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.

您不能*exec()命令一起使用(您需要一个 shell)。一个解决方案可能是编写一个脚本,然后exec()从您的 Java 应用程序编写该脚本。

回答by user1225148

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

Runtim.exec() 不使用 shell 来执行命令。因此通配符没有扩展。尝试从 java 调用 linux shell 命令中解释的解决方案