Here is an example using Apache Commons Lang SystemUtils :
public static boolean shutdown(int time) throws IOException { String shutdownCommand = null, t = time == 0 ? "now" : String.valueOf(time); if(SystemUtils.IS_OS_AIX) shutdownCommand = "shutdown -Fh " + t; else if(SystemUtils.IS_OS_FREE_BSD || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC|| SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_NET_BSD || SystemUtils.IS_OS_OPEN_BSD || SystemUtils.IS_OS_UNIX) shutdownCommand = "shutdown -h " + t; else if(SystemUtils.IS_OS_HP_UX) shutdownCommand = "shutdown -hy " + t; else if(SystemUtils.IS_OS_IRIX) shutdownCommand = "shutdown -y -g " + t; else if(SystemUtils.IS_OS_SOLARIS || SystemUtils.IS_OS_SUN_OS) shutdownCommand = "shutdown -y -i5 -g" + t; else if(SystemUtils.IS_OS_WINDOWS_XP || SystemUtils.IS_OS_WINDOWS_VISTA || SystemUtils.IS_OS_WINDOWS_7) shutdownCommand = "shutdown.exe -s -t " + t; else return false; Runtime.getRuntime().exec(shutdownCommand); return true; }
This method takes into account much more operating systems than any of the above answers. It also looks much nicer and more reliable than checking the os.name property.
Edit: Now the user has the option to enter a delay if they like!
Kezz101 Jan 12 '13 at 19:56 2013-01-12 19:56
source share