Question

Existe-t-il un moyen d’arrêter un ordinateur à l’aide d’une méthode Java intégrée ?

Était-ce utile?

La solution

Créez votre propre fonction pour exécuter un système d'exploitation commande à travers le ligne de commande?

Par souci d'exemple.Mais sachez où et pourquoi vous voudriez l’utiliser, comme le notent d’autres.

public static void main(String arg[]) throws IOException{
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("shutdown -s -t 0");
    System.exit(0);
}

Autres conseils

Voici un autre exemple qui pourrait fonctionner sur plusieurs plates-formes :

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);
}

Les commandes d'arrêt spécifiques peuvent nécessiter différents chemins ou privilèges administratifs.

Voici un exemple utilisant Apache Commons Lang's 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;
}

Cette méthode prend en compte beaucoup plus de systèmes d'exploitation que n'importe laquelle des réponses ci-dessus.Il est également beaucoup plus joli et plus fiable que de vérifier le os.name propriété.

Modifier: Prend en charge le délai et toutes les versions de Windows (inc.8/10).

La réponse rapide est non.La seule façon de le faire est d'invoquer les commandes spécifiques au système d'exploitation qui entraîneront l'arrêt de l'ordinateur, en supposant que votre application dispose des privilèges nécessaires pour le faire.Ceci n'est pas intrinsèquement portable, vous devez donc soit savoir où votre application s'exécutera, soit disposer de différentes méthodes pour différents systèmes d'exploitation et détecter laquelle utiliser.

J'utilise ce programme pour éteindre l'ordinateur en X minutes.

   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");
    }
 }

Mieux vaut utiliser .startsWith que .equals ...

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();
}

fonctionne bien

Ra.

Vous pouvez utiliser JNI pour le faire de la manière dont vous le feriez avec C/C++.

Sous Windows Embedded, par défaut, il n'y a pas de commande d'arrêt dans cmd.Dans ce cas, vous devez ajouter cette commande manuellement ou utiliser la fonction ExitWindowsEx de win32 (user32.lib) en utilisant JNA (si vous voulez plus de Java) ou JNI (si plus facile pour vous, il sera de définir des privilèges dans le code C).

ligne simple facile

Runtime.getRuntime().exec("shutdown -s -t 0");

mais ne fonctionne que sous Windows

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top