Pregunta

¿Hay alguna forma de apagar una computadora usando un método Java incorporado?

¿Fue útil?

Solución

Cree su propia función para ejecutar un sistema operativo comando a través de la línea de comandos ?

Por el bien de un ejemplo. Pero sepa dónde y por qué querría usar esto como lo notan otros.

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

Otros consejos

Aquí hay otro ejemplo que podría funcionar multiplataforma:

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

Los comandos de apagado específicos pueden requerir diferentes rutas o privilegios administrativos.

Aquí hay un ejemplo que utiliza 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;
}

Este método tiene en cuenta muchos más sistemas operativos que cualquiera de las respuestas anteriores. También se ve mucho mejor y es más confiable que verificar la propiedad os.name .

Editar: admite demoras y todas las versiones de Windows (inc. 8/10).

La respuesta rápida es no. La única forma de hacerlo es invocar los comandos específicos del sistema operativo que harán que la computadora se apague, asumiendo que su aplicación tiene los privilegios necesarios para hacerlo. Esto es intrínsecamente no portátil, por lo que debería saber dónde se ejecutará su aplicación o tener diferentes métodos para diferentes sistemas operativos y detectar cuál usar.

Utilizo este programa para apagar la computadora en X minutos.

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

Mejor uso .startsWith que uso .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();
}

funciona bien

Ra.

Puedes usar JNI para hacerlo de la manera que lo hagas con C / C ++.

En Windows Embedded por defecto, no hay un comando de apagado en cmd. En tal caso, necesita agregar este comando manualmente o usar la función ExitWindowsEx de win32 (user32.lib) utilizando JNA (si desea más Java) o JNI (si es más fácil para usted establecer los privilegios en el código C).

línea simple sencilla

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

pero solo funciona en Windows

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top