Question

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.

Was it helpful?

Solution 3

@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.

OTHER TIPS

No. There is not.

This is outside the scope of the JVM or standard Java class library.

Happy coding.

Why not use schedulers? All major operating systems supports such feature(cron, at etc). There may be other factors like permission which comes to play in modern windows (windows 7 ), linux etc.

If you want to really use some system call, Try using JNA. That simplifies platform specific access a lot.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top