10

Is it possible to shutdown Windows programmatically with Java?

Cheers

RailsSon
  • 19,897
  • 31
  • 82
  • 105
  • Possible duplicate of [Shutting down a computer](http://stackoverflow.com/questions/25637/shutting-down-a-computer) – Adi Nov 19 '15 at 03:39

4 Answers4

20
String shutdownCmd = "shutdown -s";
Process child = Runtime.getRuntime().exec(shutdownCmd);

More information on the shutdown command for your viewing pleasure

Some other command line options that may be of interest to you are

-i Display GUI interface, must be the first option

-l Log off (cannot be used with -m option)

-r Shutdown and restart the computer

-m \computername (Remote computer to shutdown/restart/abort)

-t xx Set timeout for shutdown to xx seconds

-c "comment" Shutdown comment (maximum of 127 characters)


Of course, if you prefer to not do it this method, there are libraries you can download to achieve this. One example of this would be Java Windows Shutdown Functions.

According to their SourceForge page:

JWSF - Java Windows Shutdown Functions API allows java applications to perform the following operations on most windows operating system, shutdown, restart, logoff, lock workstation. JWSF makes native calls using JNI. JWSF is subject to the LGPL license

Tom
  • 677
  • 7
  • 21
Dan McGrath
  • 41,220
  • 11
  • 99
  • 130
3

Run the command "shutdown -s".

Edit: Something like this:

Process p = Runtime.getRuntime().exec("shutdown -s");
k_b
  • 2,470
  • 18
  • 9
3

This can also be done using WMI, for example via JACOB:

import java.util.Enumeration;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;

public abstract class Shutdown {

    public static void main(String[] args) {
        ComThread.InitMTA();
        try {
            ActiveXComponent wmi = new ActiveXComponent("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\\\.");
            Variant instances = wmi.invoke("InstancesOf", "Win32_OperatingSystem");
            Enumeration<Variant> en = new EnumVariant(instances.getDispatch());
            ActiveXComponent os =
                new ActiveXComponent(en.nextElement().getDispatch());
            os.invoke("Win32Shutdown", 1, 0);
        } finally {
            ComThread.Release();
        }
    }

}
finnw
  • 47,861
  • 24
  • 143
  • 221
  • Why would you ever want to do this? Is there a particular situation this would be better? It looks a lot more complicated then using the shutdown command! – Hassan Mahmud May 30 '18 at 21:24
1

If you want to shutdown it in certain time append -t parameter (in seconds).

For five seconds:

String shutdownCmd = "shutdown -s -t5";
Carlos Landeras
  • 11,025
  • 11
  • 56
  • 82