Ver Mensaje Individual
  #2 (permalink)  
Antiguo 29/04/2015, 13:21
Avatar de Profesor_Falken
Profesor_Falken
 
Fecha de Ingreso: agosto-2014
Ubicación: Mountain View
Mensajes: 1.323
Antigüedad: 9 años, 8 meses
Puntos: 182
Respuesta: Println en cmd desde .jar

Buenas,

No puedo hacer pruebas ahora mismo en mi ordenador, pero te voy a comentar lo que creo que te pasa.

Hay dos cosas.

1.
En primer lugar, lanzas el programa pero no esperas a que termine. Por eso tu programa se termina antes de que el jar pueda ejecutarse.

Para quedarte a la espera de que el programa termine tienes que hacer un waitfor:

Código Java:
Ver original
  1. System.out.println("HOLA");
  2.         try {
  3.             Process p = Runtime.getRuntime().exec("java -jar C:\\Mundo.jar");
  4.             p.waitFor();
  5.         } catch (IOException e) {
  6.             e.printStackTrace();
  7.         } catch (InterruptedException e) {
  8.             e.printStackTrace();
  9.         }

Sin embargo, cuando lo ejecutes verás que sigue sin funcionar. Queda algo por hacer, por lo que pasamos al punto 2.

2.
Si lees la documentación de la clase Process verás lo siguiente:
Cita:
By default, the created subprocess does not have its own terminal or console. All its standard I/O (i.e. stdin, stdout, stderr) operations will be redirected to the parent process, where they can be accessed via the streams obtained using the methods getOutputStream(), getInputStream(), and getErrorStream(). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, or even deadlock.
En definitiva, lo que te está diciendo es que el comando ejecutado no saca su salida automaticamente a la consola, sino que debes hacer tu:

Código Java:
Ver original
  1. System.out.println("HOLA");
  2.         try {
  3.             Process p = Runtime.getRuntime().exec("java -jar C:\\Mundo.jar");
  4.             BufferedReader output = new BufferedReader(new InputStreamReader(p.getInputStream()));
  5.             BufferedReader error = new BufferedReader(new InputStreamReader(p.getErrorStream()));
  6.  
  7.           String linea= "";
  8.  
  9.             while ((linea= output.readLine()) != null) {
  10.                 System.out.println(linea);
  11.             }
  12.            
  13.             while ((linea= error.readLine()) != null) {
  14.                 System.out.println(linea);
  15.             }
  16.  
  17.             p.waitFor();
  18.         } catch (IOException e) {
  19.             e.printStackTrace();
  20.         } catch (InterruptedException e) {
  21.             e.printStackTrace();
  22.         }

Un saludo
__________________
If to err is human, then programmers are the most human of us