我正在嘗試關閉Windows操作系統的以下Java代碼。我正在使用使用Netbeans IDE 6.9.1的Microsoft Windows XP Professional版本2002,Service Pack 3與Intel(R)Core(TM)i3 CPU。使用Java代碼關閉windows操作系統
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()方法中倒數第二個。這段代碼有什麼問題?
在該行放置一個斷點並查看shutdownCommand是什麼。我認爲它沒有設置。嘗試取消註釋拋出異常。這段代碼還有很多其他的錯誤,但讓我們從這裏開始。 –
我在上面的代碼中修改了這行'else if(「Windows」.equals(operatingSystem)) 'else if(「Windows XP」.equals(operatingSystem))'並且窗口成功關閉。 – Lion
另請注意,您可能不允許運行此命令。你的代碼應該正確處理這種情況。 –