12
Shut Down with Runtime class
Hello Allđź‘‹ I hope you all are doing well. In this very short article I'll be writing about how you can shut down your system using Runtime class in Java.
Java Runtime class is used to interact with java runtime environment. Java Runtime class provides methods to execute a process, invoke GC, get total and free memory etc. There is only one instance of java.lang.Runtime class is available for one java application.
Let's not get much into Runtime class and see how to shut down your pc.
For doing so we must know a few things first:-
This method returns the runtime object associated with the current Java application. This is a static method of Runtime class, to know more about static method read my last article static keyword in Java, since this is a static method we will call this method without creating an object of the class.
Runtime.getRuntime();
To execute a system command we pass the command string to the exec() method of the Runtime class. The exec() method returns a Process object that abstracts a separate process executing the command. From the Process object we can get outputs from and send inputs to the command. To use this method we will call it using method().method() syntax since both the methods are of same class.
Runtime.getRuntime().exec();
To shut down we will use the command shutdown -s. We can also specify the time after which you want to make your computer shut down.
import java.lang.Runtime;
import java.util.Scanner;
public class ShutDown {
public static void main(String[] args)throws Exception {
Scanner sc = new Scanner(System.in);
System.out.println("Enter Password");
String pass = sc.next();
if(pass.equals("xyz")) {
System.out.println("Welcome, you entered correct password");
}
else {
System.out.println("You entered wrong password, soon your machine will shut down automaticallly");
run.exec("shutdown -s");
}
}
}
- On replacing line number 14 with below code you can shut down your pc after specified time
run.exec("shutdown -s -t");
- On replacing line number 14 with below code you can restart your pc
run.exec("shutdown -r");
- On replacing line number 14 with below code you can restart your pc after specified time
run.exec("shutdown -r -t");
- On replacing line number 14 with below code you can log out of your pc
run.exec("shutdown -l");
- On replacing line number 14 with below code you can log out of your pc after specified time
run.exec("shutdown -l -t");
- On replacing line number 14 with below code you can lock your pc
run.exec("c:/windows/system32/rundll32.exe user32.dll, LockWorkStation");
import java.io.IOException;
public class SystemApp {
public static void main(String[] args) {
try {
Runtime run = Runtime.getRuntime();
String path = "C:\\Users\\hp\\AppData\\Local\\Programs\\Microsoft VS Code\\Code.exe";
Process process = run.exec(path);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Cover:- Rajat Gour
My personal blog blog.ritvikdubey.com
12