コンピューターをシャットダウンする
-
09-06-2019 - |
質問
組み込みのJavaメソッドを使用してコンピューターをシャットダウンする方法はありますか?
他のヒント
クロスプラットフォームで機能する別の例を次に示します。
public static void shutdown() throws RuntimeException, 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);
}
特定のシャットダウンコマンドには、異なるパスまたは管理者権限が必要な場合があります。
Apache Commons Langの SystemUtils :
public static boolean shutdown(int time) throws IOException {
String shutdownCommand = null, t = time == 0 ? "now" : String.valueOf(time);
if(SystemUtils.IS_OS_AIX)
shutdownCommand = "shutdown -Fh " + t;
else if(SystemUtils.IS_OS_FREE_BSD || SystemUtils.IS_OS_LINUX || SystemUtils.IS_OS_MAC|| SystemUtils.IS_OS_MAC_OSX || SystemUtils.IS_OS_NET_BSD || SystemUtils.IS_OS_OPEN_BSD || SystemUtils.IS_OS_UNIX)
shutdownCommand = "shutdown -h " + t;
else if(SystemUtils.IS_OS_HP_UX)
shutdownCommand = "shutdown -hy " + t;
else if(SystemUtils.IS_OS_IRIX)
shutdownCommand = "shutdown -y -g " + t;
else if(SystemUtils.IS_OS_SOLARIS || SystemUtils.IS_OS_SUN_OS)
shutdownCommand = "shutdown -y -i5 -g" + t;
else if(SystemUtils.IS_OS_WINDOWS)
shutdownCommand = "shutdown.exe /s /t " + t;
else
return false;
Runtime.getRuntime().exec(shutdownCommand);
return true;
}
この方法では、上記の回答よりもはるかに多くのオペレーティングシステムが考慮されます。また、 os.name
プロパティを確認するよりもずっと見栄えがよく、信頼性も高くなります。
編集:遅延とすべてのバージョンのWindows(8/10を含む)をサポートしています。
簡単な答えはノーです。それを行う唯一の方法は、アプリケーションに必要な特権があると仮定して、コンピューターをシャットダウンするOS固有のコマンドを呼び出すことです。これは本質的に移植性がないため、アプリケーションが実行される場所を知るか、OSごとに異なるメソッドを使用して、どちらを使用するかを検出する必要があります。
このプログラムを使用して、X分でコンピューターをシャットダウンします。
public class Shutdown {
public static void main(String[] args) {
int minutes = Integer.valueOf(args[0]);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
ProcessBuilder processBuilder = new ProcessBuilder("shutdown",
"/s");
try {
processBuilder.start();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}, minutes * 60 * 1000);
System.out.println(" Shutting down in " + minutes + " minutes");
}
}
.equalsを使用するよりも.startsWithを使用する方が良い...
String osName = System.getProperty("os.name");
if (osName.startsWith("Win")) {
shutdownCommand = "shutdown.exe -s -t 0";
} else if (osName.startsWith("Linux") || osName.startsWith("Mac")) {
shutdownCommand = "shutdown -h now";
} else {
System.err.println("Shutdown unsupported operating system ...");
//closeApp();
}
正常に動作
Ra。
JNI を使用して、Cでどのような方法でも実行できます。 / C ++。
Windows Embeddedでは、デフォルトでcmdにシャットダウンコマンドはありません。 このような場合、このコマンドを手動で追加するか、JNA(Javaが必要な場合)またはJNI(Cコードで特権を設定する方が簡単な場合)を使用してwin32(user32.lib)からExitWindowsEx関数を使用する必要があります。
簡単な単一行
Runtime.getRuntime().exec("shutdown -s -t 0");
ただし、Windowsでのみ動作します