繁体   English   中英

使用Java代码关闭Windows操作系统

[英]Shutting down windows operating system using Java code

我正在尝试以下Java代码关闭Windows操作系统。 我正在使用Microsoft Windows XP Professional版本2002,Service Pack 3和使用NetBeans IDE 6.9.1的Intel(R)CoreTM i3 CPU

package shutdownos;

import java.io.IOException;

final public class Main
{
    public static void main(String... args) throws 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);
    }
}

它在Java中引发以下异常。

Exception in thread "main" java.lang.IllegalArgumentException: Empty command

上面的代码中的以下行发生异常。

Runtime.getRuntime().exec(shutdownCommand);

main()方法中倒数第二个。 此代码有什么问题?

您正在寻找错误的os.name值-不管它是什么,它都不是“ Windows”,因此代码运行在else块中,在该块中,变量shudowncommand保留为空字符串,这会导致“ Empty命令”例外。 执行System.out.println(operatingSystem)以查看应检查的值,而不是“ Windows”。

这也可能是类似“Windows NT的”,因此,如果您更换.equals()通过检查.startsWith()检查你应该设置。

根据页面,您似乎对O / S名称使用了错误的值。 如果是这样,您的shutdownCommand字符串将保持为空,这将导致您的程序传递一个空命令,该命令与您所获取的异常一致。

该程序正在跳过两个if语句,os.name不仅仅是Windows,而是我认为Windows XP或更高版本,所以将其替换为

else if (operatingSystem.startsWith("Windows")){

 }

没有等于“ Windows”的属性“ os.name”。 您是否要检查该属性是否包含“ Windows”? 据我所知,所有窗口操作系统名称都有一个量词,例如“ Windows 95”,“ Windows NT”等。

Windows操作系统的关闭命令应为shutdown -s -t 0 试试这个。

我主要使用此站点来查找可能的值: 我可以使用什么os或arch值?

正如其他人所说,您应该使用String.startsWith()方法。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM