How to shut down a Computer from a Java application

A developer may need to shut down a computer from a Java application. This post explains how it can be done.


Ways to identify operating system

In all solutions proposed here we are calling the OS directly to shutdown the computer.

Inside Runtime class, you can call the run() method that runs directly the string as a command on system terminal.

As the command to shutdown a computer may differ on each operating system, you need to identify the corresponding scenario and execute the corresponding command.

Method 1. Identify OS using System.getProperty(“”)

Here, we make use of System.getProperty(“”) method to get a string with the OS.

public static void shutdown() throws RuntimeException, IOException {
String shutdownCommand;
String operatingSystem = System.getProperty("");
if ("Linux".equals(operatingSystem) || "Mac OS X".equals(operatingSystem)) {
shutdownCommand = "shutdown -h now";
else if ("Windows".equals(operatingSystem)) {
shutdownCommand = "shutdown.exe -s -t 0";
else {
throw new RuntimeException("Unsupported operating system.");

Method 2. Identifying OS using Apache Common Languages’ SystemUtils

The developer can use SystemUtils class to identify the operating system.
public static boolean shutdown(int time) throws IOException {
String shutdownCommand = null, t = time == 0 ? "now" : String.valueOf(time);
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)
shutdownCommand = "shutdown.exe /s /t " + t;
return false;
return true;


External references

Leave a Reply

Your email address will not be published. Required fields are marked *