I have this program that I must run from another.
public class Exercici8_p1 {
public static void main(String[] args) {
System.out.println("Introduzca texto -> ");
Scanner sc = new Scanner(System.in);
String texto = sc.nextLine();
String[] parts = texto.split("\\*");
System.out.println(parts[0]);
}
}
From this I must execute the previous one
public class Exercici8_p1b {
public static void main(String[] args) {
try
{
Process process = Runtime.getRuntime().exec("java Exercici8_p1");
}
catch(Exception e)
{
System.err.println("Error on exec() method");
}
}
}
The problem with your code and so you don't 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 modifications:
Now the second, the use of
Runtime.getRuntime().exec()
is somewhat obsolete, to correctly process the input and output of both input and errors from the process, threads must be used to work at the same time, for this reason a specific class was developed to hide the processing required, the classProcessBuilder
.Here is an example that will allow you to run your first example class:
The method
InheritIO
allows you to associate the input and output streams with the current streams of your program, so that you can write and read the program interactively as if you had run it directly.I don't understand what is the purpose of your target but you can do two things: 1. Create that as a class:
You can create your Exercici8_p1 as a class and create a normal method with what you have in main, from the other program you can create an object of type Exercici8_p1 and call the method.
Remember that the type of programming that is being used is imperative programming where there is a flow of instructions, therefore calling another program is enough to run one more method, but if you want to create another process just launch one more thread.
https://jarroba.com/multitasking-and-threads-in-java-with-examples-thread-runnable/