自己学习Runtime.getRuntime().exec()之后明白其用法,但是总结不出它的功能,在查阅网上资料找到一个比较通俗易懂且全面的答案:在java中,RunTime.getRuntime().exec()实现了调用服务器命令脚本来执行功能需要。
如果我们想在500秒后使电脑关机则需要在运行中输入 cmd ,打开命令弹框中输入:
//添加一个60S后自动关闭计算机的计划。
shutdown -s -t 500
通过Runtime.getRuntime().exec()我们可以这样写
//添加一个60S后自动关闭计算机的计划。
Runtime.getRuntime().exec(shutdown -s -t 500);
下面展示具体例子。
在这里使用Runtime.getRuntime().exec()会提示异常,我们将它抛出即可。
import java.io.IOException;
import java.util.Scanner;
public class Demo7 {
public static void main(String[] args) throws IOException {
System.out.println("欢迎来到自动关机程序");
//用于创建接收用户输入的变量input
Scanner input = new Scanner(System.in);
System.out.println("请输入电脑关机倒计时时间(s)");
//获取用户输入信息
String text = input.nextLine();
//关机指令shutdown -s -t 时间
Runtime.getRuntime().exec("shutdown -s -t "+text);
System.out.println("你的电脑将在"+text+"s后关机");
System.out.println("如想取消关机请输入1");
//用于创建接收用户输入的变量input1
Scanner input1 = new Scanner(System.in);
//获取用户输入信息
String text1 = input1.nextLine();
//将String(字符串)型text1转换为int整型b
int b=Integer.parseInt(text1);
//判定b是否等于1
if(b==1) {
//取消关机指令
Runtime.getRuntime().exec("shutdown -a");
System.out.println("关机已经取消");
}
}
}