2008-08-25 11 views

Respuesta

75

Crea tu propia función para ejecutar un sistema operativo command a través del command line?

Por el bien de un ejemplo. Pero sepa dónde y por qué querría usar esto, como señalan los demás.

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

1 no hay nada más que esta línea java - tiempo de ejecución en tiempo de ejecución = Runtime.getRuntime(); – BRampersad

+2

¿Funcionará esto solo en Windows o en cualquier lugar? –

+4

Esto funcionará solo en Windows. – partlov

22

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

2

Puede usar JNI para hacerlo de la manera que lo haría con C/C++.

71

Aquí hay otro ejemplo que podría trabajar 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 específicos de apagado puede requerir diferentes caminos o privilegios administrativos.

+0

Mi único problema con esto es el futuro. ¿Qué pasa si sale otro tipo de sistema operativo y alguien hace una JVM para eso? – Supuhstar

+15

luego agrega la nueva condición ... el software nunca se termina. – Gubatron

5

Mejor uso de .startsWith .equals uso ...

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

trabajo fino

Ra.

+22

Hasta que alguien use un nuevo sistema operativo llamado Macaroni donde shutdown es el comando de autodestrucción. –

8

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

En Windows Incrustado de forma predeterminada, no hay ningún comando de apagado en cmd. En tal caso, necesita agregar este comando manualmente o usar la función ExitWindowsEx de win32 (user32.lib) usando JNA (si desea más Java) o JNI (si le resulta más fácil, configurará privilegios en el código C).

27

Aquí hay un ejemplo usando Apache Commons Lang'sSystemUtils:

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_XP || SystemUtils.IS_OS_WINDOWS_VISTA || SystemUtils.IS_OS_WINDOWS_7) 
     shutdownCommand = "shutdown.exe -s -t " + t; 
    else 
     return false; 

    Runtime.getRuntime().exec(shutdownCommand); 
    return true; 
} 

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

Editar: ¡Ahora tiene la opción de que el usuario ingrese un retraso si lo desea!

+0

¡Muchas gracias, esto es muy útil! ¿Conoces alguna forma similar de dormir una computadora en cada sistema operativo? – JFreeman

+0

También me pregunto si esto funciona para Windows 8+? – JFreeman

0

fácil de una sola línea

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

pero sólo funciona en Windows

Cuestiones relacionadas