从JAVA问题执行Unix系统命令 [英] Execute Unix system command from JAVA problem
问题描述
从JAVA代码执行系统命令时,我遇到了一个奇怪的问题.
实际上,我想从我的JAVA应用程序中获取Mac OSX
系统信息.
为此,我使用
I am facing a weird issue with executing a system command from JAVA code.
Actually i want to get the Mac OSX
system information from my JAVA App.
For that im using
Runtime.getRuntime().exec("system_profiler -detailLevel full");
这工作正常.如果我打印输出,那很酷.
但是我想将此信息写入plist
文件以供将来使用.为此,我使用system_profiler
.like,
This is working fine.If i print the output,it is cool.
But i want to write this information to a plist
file for future use.For that im using the -xml argument of system_profiler
.like,
String cmd = "system_profiler -detailLevel full -xml > "+System.getProperty( "user.home" )+"/sysinfo.plist";
Process p = Runtime.getRuntime().exec(cmd);
基本上,这应该在当前用户的主目录中创建一个plist文件.
Basically this should create a plist file in the current users home directory.
但是,这似乎没有在文件中写入任何内容.
But this seems to be not writing anything to file.
我在这里想念什么吗?
推荐答案
我的Java不仅生锈,所以请保持柔和. ;-)
My Java is more than rusty, so please be gentle. ;-)
-
Runtime.exec()
不会自动使用外壳执行您传递的命令,因此IO重定向没有做任何事情.
Runtime.exec()
does not automatically use the shell to execute the command you passed, so the IO redirection is not doing anything.
如果您仅使用:
"/bin/sh -c system_profiler -detailLevel full > path/file.plist"
然后该字符串将被标记为:
Then the string will be tokenized into:
{ "/bin/sh", "-c", "system_profiler", "-detailLevel", "full", ">", "path/file.plist" }
这也是行不通的,因为-c
只需要一个参数.
Which also wouldn't work, because -c
only expects a single argument.
尝试以下方法:
String[] cmd = { "/bin/sh", "-c", "system_profiler -detailLevel full > path/file.plist" };
Process p = Runtime.getRuntime.exec(cmd);
当然,您也可以使用Process.getInputStream()
读取Process
实例的输出,并将其写入所需的文件中.因此,完全跳过外壳程序,IO重定向等.
Of course, you could also just read the output of your Process
instance using Process.getInputStream()
and write that into the file you want; thus skip the shell, IO redirection, etc. altogether.
这篇关于从JAVA问题执行Unix系统命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!