Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shutting down a computer

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

like image 336
jjnguy Avatar asked Aug 25 '08 04:08

jjnguy


People also ask

Does shutting down your computer delete everything?

Restarting a computer doesn't 'delete everything' and it's the surprising solution to many common PC problems. It's good advice for everyone to restart their computers weekly, whether you need to or not.


2 Answers

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); } 
like image 119
David McGraw Avatar answered Oct 01 '22 12:10

David McGraw


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.

like image 31
David Crow Avatar answered Oct 01 '22 10:10

David Crow