I'm trying to get the result from a .class, calling the process on another .java. The formatting of both files is as follows:
package Ejemplo2;
import java.io.*;
public class Ejemplo2 {
public static void main(String[] args) throws IOException {
Process p = new ProcessBuilder("ls", "-la").start();
try {
InputStream is = p.getInputStream();
int c;
while ((c = is.read()) != -1) {
System.out.print((char) c);
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
int exitVal;
try {
exitVal = p.waitFor(); //recoge la salida de System.exit()
System.out.println("Valor de Salida: " exitVal);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
and
package Ejemplo3;
import java.io.*;
public class Ejemplo3 {
public static void main(String[] args) throws IOException{
File directorio = new File("./out/production/psp-2122/Ejemplo2");
ProcessBuilder pb = new ProcessBuilder("java", "Ejemplo2");
pb.directory(directorio);
System.out.printf("Directorio de trabajo: %s%n",pb.directory());
Process p = pb.start();
try {
InputStream is = p.getInputStream();
for (int i = 0; i<is.available(); i ) {
System.out.println("" is.read());
}
is.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The result only displays the directory and the exit code, but I don't really have a clue why the process itself is not shown.
CodePudding user response:
You should probably do:
// start in classes root
File directorio = new File("./out/production/psp-2122");
// Run java with fully qualified class name Ejemplo2.Ejemplo2
ProcessBuilder pb = new ProcessBuilder("java", "Ejemplo2.Ejemplo2");
CodePudding user response:
You aren't seeing any of the error messages as you are not reading any of the error streams. The simplest approach is to just redirect standard ERROR -> OUTPUT before calling start()
:
ProcessBuilder pb = new ProcessBuilder(cmd);
pb.redirectErrorStream(true);
Process p = pb.start();
Save yourself some typing, replace the while
/ for
loops through the standard output streams with:
try(var stdout = p.getInputStream()) {
stdout.transferTo(System.out);
}
Always call waitFor
at the end so that you know the process completion:
int exitVal = pb.waitFor();