在 Linux 中关闭计算机的Java程序
在这个程序中,如果操作系统是 Linux,我们将关闭计算机。因此,首先我们将检查我们运行Java程序的系统是否为 Linux。如果操作系统不是 Linux,那么我们将不会继续并打印“不支持的操作系统”。如果是 Linux 操作系统,则用户将输入时间(以秒为单位),以便在该时间之后 PC 将关闭。
这里的时间(以秒为单位)不包括您的系统关闭所需的时间。例如:如果用户将输入 1 秒,则它由 1 秒加上您关闭所需的系统时间组成。这是因为系统架构、RAM 的可用性等会影响关机速度。
方法:
- 导入所需的包。
- 检查您的 PC 是否装有 Linux 操作系统。
- 如果不是 Linux,则打印“不支持的操作系统”。
- 如果是 Linux,则向用户输入有关“PC 将在多少秒后关闭”的输入。
- PC 将关闭。
下面是上述方法的实现:
Java
// Java Program to Shut Down Computer
// when Operating System is Linux.
import java.io.IOException;
import java.util.Scanner;
public class SystemShutDown {
public static void main(String args[])
throws IOException
{
// Initialized to take input from user in seconds
int seconds;
// Find Out Operating System
String operatingSystem
= System.getProperty("os.name");
// Print Operating System of Computer
System.out.println("Name of Operating System:"
+ operatingSystem);
// Check if Computer Operating System is Linux or
// not
if (operatingSystem.equals("Linux")) {
// Returns the runtime object associated with
// the current Java application.
Runtime runTime = Runtime.getRuntime();
// Take input from user in seconds
seconds = 5;
// Retrieve current Runtime Enviornment
Process processing
= runTime.exec("shutdown -h -t " + seconds);
// Shutting Down the System
System.exit(0);
}
输出:
Name of Operating System:Linux
//Shutting Down your Linux system