javaplatform-independentsystem-shutdownplatform-independence

System-independent machine shutdown in Java


Possible Duplicate:
Shutting down a computer using Java

I am making a personal program that will shut down my computer after a certain amount of time or at a certain time/date. However, I am running multiple operating systems and want to do this with one simple Java program. Is there any way to send a system-independent machine shutdown request in Java without any using any external libraries? I know you can use java.awt.Desktop.getDesktop().browse(new URI("shutdown /s")); in Windows, but, again, I want system independence.


Solution

  • @robjb gave me the best solution. Though it is a little too inflexible for my tastes, I will be suing it until I run into a problem.

      String shutdownCommand;
      StringPP operatingSystem = new StringPP(System.getProperty("os.name"));
    
      if (operatingSystem.containsIgnoreCase("linux") ||
          operatingSystem.containsIgnoreCase("mac") ||
          operatingSystem.containsIgnoreCase("unix"))
      {
        shutdownCommand = "sudo shutdown -h -t 30";
      }
      else if (operatingSystem.containsIgnoreCase("windows"))
      {
        shutdownCommand = "shutdown /s /d P:0:0 /t 30 /c \"Blue Husky Timer 2 is shutting down your system, as you requested. \n"
            + "You have 30 seconds to save and close programs\"";
      }
      else
      {
        throw new UnsupportedOperationException("Unsupported operating system.");
      }
    
      try
      {
        Runtime.getRuntime().exec(shutdownCommand);
      }
      catch (Throwable t)
      {
        Main.LOG.logThrowable(t);
      }
      System.exit(0);
    

    In the above example, StringPP is a custom class that augments the capabilities of a String with methods such as the above used #containsIgnoreCase. Main.LOG is a logging utility that I made and use.