The problem with your code and why you do not know if it works or not is because you are not printing anything from the process you are running, for this you can make these changes:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Exercici8_p1b {
public static void main(String[] args) {
try {
Process proc = Runtime.getRuntime().exec("dir");
BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
// leer la salida de correr el proceso
System.out.println("Salida del comando:\n");
String s;
while ((s = stdInput.readLine()) != null) {
System.out.println(s);
}
BufferedReader stdError = new BufferedReader(new InputStreamReader(proc.getErrorStream()));
// leer errores ak ejecutar el comando
System.out.println("Salida de errores del proceso (si los hay):\n");
while ((s = stdError.readLine()) != null) {
System.out.println(s);
}
} catch (IOException e) {
System.err.println("Error al ejecutar");
}
}
}
Now the second, the use of Runtime.getRuntime().exec()
is somewhat obsolete, to correctly process the input and output both input and errors from the process should use threads to work at the same time, so it developed a specific class to hide the required processing, class ProcessBuilder
.
Here is an example that will allow you to run your first example class:
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
public class Exercici8_p1c1 {
public static void main(String[] args) {
try {
Path currentRelativePath = Paths.get("");
String ss = currentRelativePath.toAbsolutePath().toString();
System.out.println("La ruta desde donde ejecutas tu comando es: " + ss);
ProcessBuilder builder = new ProcessBuilder("java", "Exercici8_p1");
builder.redirectErrorStream(true);
builder.inheritIO();
Process process = builder.start();
int errCode = process.waitFor();
System.out.println("Error al ejecutar el comando? " + (errCode == 0 ? "No" : "Sí"));
} catch (IOException e) {
System.err.println("Error de lectoescritura");
} catch (InterruptedException ex) {
System.err.println("Problema con los hilos");
}
}
}
The InheritIO
method allows you to associate the input and output flows to the current flows of your program, so you can write and read the program interactively as if you had run it directly.