关闭计算机

新手上路,请多包涵

有没有办法使用内置的 Java 方法关闭计算机?

原文由 jjnguy 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 553
2 个回答

创建您自己的函数以通过 命令行 执行操作系统命令?

举个例子。但是要知道你想在哪里以及为什么要使用它,就像其他人所说的那样。

 public static void main(String arg[]) throws IOException{
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("shutdown -s -t 0");
    System.exit(0);
}

原文由 David McGraw 发布,翻译遵循 CC BY-SA 4.0 许可协议

这是另一个可以跨平台工作的例子:

 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";
    }
    // This will work on any version of windows including version 11
    else if (operatingSystem.contains("Windows")) {
        shutdownCommand = "shutdown.exe -s -t 0";
    }
    else {
        throw new RuntimeException("Unsupported operating system.");
    }

    Runtime.getRuntime().exec(shutdownCommand);
    System.exit(0);
}

特定的关机命令可能需要不同的路径或管理权限。

原文由 David Crow 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
logo
Stack Overflow 翻译
子站问答
访问
宣传栏