try { Runtime.getRuntime().exec("shutdown /h"); } catch (IOException ex) {}
Tutorials, tips and tricks about java programming language. Answers for many doubts about java programming language. Answering many howtos. Sample java projects and source code, java games, java programs for java practical labs.
Search This Blog
Java Program to Hibernate Windows Operating System
How to Shutdown Computer from Java - Java Code to Shutdown Computer
try { String command; String os = System.getProperty("os.name").toLowerCase(); if (os.contains("linux") || os.contains("mac os x")) command = "shutdown -h now"; else if (os.contains("windows")) command = "shutdown /p"; else throw new Exception("Unsupported operating system."); Runtime.getRuntime().exec(command); System.exit(0); } catch (Exception ex) { JOptionPane.showMessageDialog(null, ex.getMessage()); }
For Linux and Mac OS X, the command for immediate shutdown is shutdown -h now. But in Windows, it is shutdown /p. The above java code checks the operating system. Then it assumes appropriate shutdown command and then executes it. This java code can shutdown a computer.
How to Get Operating System Information in Java
Using java, you can gather some information about the operating system of the computer system on which the code is running. That us java provides some API classes that will help you to know about the operating system of the computer on which your application program is running. You can use System.getProperty() method for this purpose. There are some system property keys (strings) which can be used to get the respective information. The parameter to the System.getProperty() method is a string, the property key. The following values for the parameter string will give operating system related informations.
"os.arch"
Operating system architecture
"os.name"
Name of the operating system.
"os.version"
Version of Operating system.