使用 Java 关闭 Windows
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2973643/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Shutdown Windows with Java
提问by RailsSon
Is it possible to shutdown Windows programmatically with Java?
是否可以使用 Java 以编程方式关闭 Windows?
Cheers
干杯
采纳答案by Dan McGrath
String shutdownCmd = "shutdown -s"
Process child = Runtime.getRuntime().exec(shutdownCmd);
More information on the shutdown commandfor your viewing pleasure
更多关于关机命令的信息,让您观看愉快
Some other command line options that may be of interest to you are
您可能感兴趣的其他一些命令行选项是
-i Display GUI interface, must be the first option
-l Log off (cannot be used with -m option)
-r Shutdown and restart the computer
-m \computername (Remote computer to shutdown/restart/abort)
-t xx Set timeout for shutdown to xx seconds
-c "comment" Shutdown comment (maximum of 127 characters)
-i 显示GUI界面,必须是第一个选项
-l 注销(不能与 -m 选项一起使用)
-r 关闭并重新启动计算机
-m \computername (要关闭/重启/中止的远程计算机)
-t xx 将关机超时设置为 xx 秒
-c "comment" 关机注释(最多 127 个字符)
Of course, if you prefer to not do it this method, there are libraries you can download to achieve this. One example of this would be Java Windows Shutdown Functions.
当然,如果您不想使用这种方法,您可以下载一些库来实现此目的。这方面的一个例子是Java Windows Shutdown Functions。
According to their SourceForge page:
根据他们的 SourceForge 页面:
JWSF - Java Windows Shutdown Functions API allows java applications to perform the following operations on most windows operating system, shutdown, restart, logoff, lock workstation. JWSF makes native calls using JNI. JWSF is subject to the LGPL license
JWSF - Java Windows Shutdown Functions API 允许 Java 应用程序在大多数 Windows 操作系统上执行以下操作,关闭、重新启动、注销、锁定工作站。JWSF 使用 JNI 进行本机调用。JWSF 受 LGPL 许可
回答by k_b
Run the command "shutdown -s".
运行命令“关机 -s”。
Edit: Something like this:
编辑:像这样:
Process p = Runtime.getRuntime().exec("shutdown -s");
回答by finnw
This can also be done using WMI, for example via JACOB:
这也可以使用 WMI 来完成,例如通过 JACOB:
import java.util.Enumeration;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.EnumVariant;
import com.jacob.com.Variant;
public abstract class Shutdown {
public static void main(String[] args) {
ComThread.InitMTA();
try {
ActiveXComponent wmi = new ActiveXComponent("winmgmts:{impersonationLevel=impersonate,(Shutdown)}!\\.");
Variant instances = wmi.invoke("InstancesOf", "Win32_OperatingSystem");
Enumeration<Variant> en = new EnumVariant(instances.getDispatch());
ActiveXComponent os =
new ActiveXComponent(en.nextElement().getDispatch());
os.invoke("Win32Shutdown", 1, 0);
} finally {
ComThread.Release();
}
}
}
回答by Carlos Landeras
If you want to shutdown it in certain time append -t parameter (in seconds).
如果要在特定时间关闭它,请附加 -t 参数(以秒为单位)。
For five seconds:
五秒钟:
String shutdownCmd = "shutdown -s -t5";