Coders Packet

Shutdown a computer using runtime command in Java

By zeel ajadiya

Hello friends! In this Java tutorial, we are going to discuss how to shut down a computer after some specific time.

To shut down a computer we need to send a signal to os, in java send the signal to os by using shutdown.exe -s -t command where t determines the time after which the system will shut down. In this code, I have used the runtime method.

Here I have first declared some library and then I have to fetch the os by using System.getProperty("os.name") command.

String operatingSystem = System.getProperty("os.name");

 

Then I use startsWith() method to see that it starts with "Win" then it is windows and accordingly, code will be executed else according to Linux or Mac commands. and windows will be shut down. 

if (operatingSystem.startsWith("Win")) {
      
                shutdown_Computer_Command = "shutdown.exe -s -t "+time_to_shutdown;
           }
        else if (operatingSystem.startsWith("Linux") || operatingSystem.startsWith("Mac")) {
                shutdown_Computer_Command = "shutdown -h now";
}
        else {
            throw new RuntimeException("Operating System name is not matched according to your os version \n NOTE:- first print the osname and edit accordingly");
}

then to shut down use 

Runtime.getRuntime().exec(shutdown_Computer_Command);

 

 

Download project

Reviews Report

Submitted by zeel ajadiya (zeel)

Download packets of source code on Coders Packet