关闭电脑
时间:2020-03-05 18:42:43 来源:igfitidea点击:
有没有一种使用内置Java方法关闭计算机的方法?
解决方案
回答
创建自己的函数以通过命令行执行OS命令吗?
为了举例。但是要知道,在其他地方以及为什么要使用它。
public static void main(String arg[]) throws IOException{ Runtime runtime = Runtime.getRuntime(); Process proc = runtime.exec("shutdown -s -t 0"); System.exit(0); }
回答
快速的答案是不。唯一的方法是调用特定于操作系统的命令,这些命令将导致计算机关闭,前提是应用程序具有执行此操作所需的特权。这本质上是不可移植的,因此我们需要知道应用程序将在何处运行,或者需要针对不同的操作系统使用不同的方法并检测要使用哪个操作系统。
回答
我们可以使用JNI来完成C / C ++的任何操作。
回答
这是另一个可以跨平台工作的示例:
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"; } else if ("Windows".equals(operatingSystem)) { shutdownCommand = "shutdown.exe -s -t 0"; } else { throw new RuntimeException("Unsupported operating system."); } Runtime.getRuntime().exec(shutdownCommand); System.exit(0); }
特定的关闭命令可能需要不同的路径或者管理特权。
回答
最好使用.startsWith比使用.equals ...
String osName = System.getProperty("os.name"); if (osName.startsWith("Win")) { shutdownCommand = "shutdown.exe -s -t 0"; } else if (osName.startsWith("Linux") || osName.startsWith("Mac")) { shutdownCommand = "shutdown -h now"; } else { System.err.println("Shutdown unsupported operating system ..."); //closeApp(); }
做工不错
镭
回答
我使用此程序在X分钟内关闭了计算机。
public class Shutdown { public static void main(String[] args) { int minutes = Integer.valueOf(args[0]); Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { ProcessBuilder processBuilder = new ProcessBuilder("shutdown", "/s"); try { processBuilder.start(); } catch (IOException e) { throw new RuntimeException(e); } } }, minutes * 60 * 1000); System.out.println(" Shutting down in " + minutes + " minutes"); } }