views:

3324

answers:

6

Is there a way to shutdown a computer using a built-in Java method?

+12  A: 

Create your own function to execute an OS command through the command line?

For the sake of an example. But know where and why you'd want to use this as others note.

public static void main(String arg[]) throws IOException{
 Runtime runtime = Runtime.getRuntime();
 Process proc = runtime.exec("shutdown -s -t 0");
 System.exit(0);
}
David McGraw
+14  A: 

The quick answer is no. The only way to do it is by invoking the OS-specific commands that will cause the computer to shutdown, assuming your application has the necessary privileges to do it. This is inherently non-portable, so you'd need either to know where your application will run or have different methods for different OSs and detect which one to use.

Wilson
A: 

You can use JNI to do it in whatever way you'd do it with C/C++.

Steve M
+15  A: 

Here's another example that could work cross-platform:

public static void shutdown() throws RuntimeException, IOException {
    String shutdownCommand;
    String operatingSystem = System.getProperty("os.name");

    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.");
    }

    Runtime.getRuntime().exec(shutdownCommand);
    System.exit(0);
}

The specific shutdown commands may require different paths or administrative privileges.

David Crow
+1  A: 

Better use .startsWith than use .equals ...

String osName = System.getProperty("os.name");        
if (osName.startsWith("Win")) {
  shutdownCommand = "shutdown.exe -s -t 0";
} else if (osName.startsWith("Linux") || osName.startsWith("Mac")) {
  shutdownCommand = "shutdown -h now";
} else {
  System.err.println("Shutdown unsupported operating system ...");
    //closeApp();
}

work fine

Ra.

Ra
Until somebody uses a new OS called Macaroni where shutdown is the self-destruct command.
Bart van Heukelom
+1  A: 

I use this program to shutdown the computer in X minutes.

   public class Shutdown {
    public static void main(String[] args) {

        int minutes = Integer.valueOf(args[0]);
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                ProcessBuilder processBuilder = new ProcessBuilder("shutdown",
                        "/s");
                try {
                    processBuilder.start();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }

        }, minutes * 60 * 1000);

        System.out.println(" Shutting down in " + minutes + " minutes");
    }
 }
Jonathan Barbero