开发者

How can a java program decide which command to execute depending of os

I have to make a program which will print the network settings using "ipconfig" for Windows and "ifc开发者_Go百科onfig" for Linux, but I need to do that with a unique implementation for both OS.


You can get the name of the operating system through

System.getProperty("os.name")

Have a look at this page for some sample code.


If it's by any chance the IP of the local host you're interested in, there are ways to get this directly in Java:

  • Getting the IP Address and Hostname of the Local Machine
  • Get the workstation name/ip

There is no way to determine what the "show ip information"-command is for an arbitrary operating system. You will have to hard-code what the command is (if the is one) for each operating system name manually.


As a complement to the other answers, I'll mention SystemUtils from Commons Lang which exposes various constant such as IS_OS_UNIX, IS_OS_WINDOWS, etc.


Building on aioobe's solution:

final String osname = System.getProperty("os.name").toLowerCase();
String processName;
if(osname.startsWith("win"))
    processName="ipconfig /some /parameter";
else
    processName="ifconfig -some -parameter";
Runtime.getRuntime().exec(processName);


For reference, here's a concrete example that sets a property only for a particular OS:

if (System.getProperty("os.name").startsWith("Mac OS X")) {
    System.setProperty("apple.awt.graphics.UseQuartz", "true");
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜