Is there a way to shutdown a computer using a built-in Java method?
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.
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); }
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With