I’m trying the following Java code to shut down Windows operating system. I’m using Microsoft Windows XP Professional version 2002, Service pack 3 with Intel(R) Core(TM) i3 CPU using Netbeans IDE 6.9.1.
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);
}
}
It throws the following exception in Java.
Exception in thread "main" java.lang.IllegalArgumentException: Empty command
The exception occurs on the following line in the above code.
Runtime.getRuntime().exec(shutdownCommand);
The second-last in the main() method. What is wrong with this code?
You’re looking for the wrong value of
os.name— whatever it is, it’s not “Windows” and therefore the code runs through theelseblock where the variableshudowncommandis left as an empty string, which causes the “Empty command” exception. Do aSystem.out.println(operatingSystem)to see what value you should check for instead of “Windows”.It’s probably something like “Windows NT”, so if you replace the
.equals()check by a.startsWith()check you should be set.