Reputation: 494
i have a hello world class hworld.class which displays "Hello World" on the console. i am trying to run it from another class in console using the code
public class ftest2
{
public static void main(String[] arg)
{
System.out.println("NEW FILE PRINT LINE EXECUTED");
try {
Process pro1 = Runtime.getRuntime().exec("javac hworld.java");
pro1.waitFor();
Process pro2 = Runtime.getRuntime().exec("java hworld");
pro2.waitFor();
} catch (Exception e) {
System.out.println("Some Error");
e.printStackTrace();
}
} }
but when the file is executed, the output of Hello World is not displayed on the console.
the program just starts and displays
NEW FILE PRINT LINE EXECUTED
insted of
NEW FILE PRINT LINE EXECUTED
HELLO WORLD
how it would be possible to display the output of HELLO WORLD as well.
(it is example program. i want to display the output of a program within another program)
if there is another way to call a class within another class to display its output. then please mention it.
Upvotes: 1
Views: 5116
Reputation: 328737
You need to redirect the inputstream of your process to System.out, for example:
public static void main(String[] arg) {
System.out.println("NEW FILE PRINT LINE EXECUTED");
try {
Process pro1 = Runtime.getRuntime().exec("javac hworld.java");
try (BufferedReader reader = new BufferedReader(new InputStreamReader(pro1.getInputStream(), Charset.forName("UTF-8")))) {
String line;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
Note: it uses the try with resources syntax of Java 7 but is easily transposable to Java 6- if necessary.
Upvotes: 1
Reputation: 2962
You need to read in the InputStream
of the process, which is
The stream obtains data piped from the standard output stream of the process represented by this Process object.
Source: http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Process.html#getInputStream()
Read InputStream
and write out to System.out
:
InputStream inputStream = process.getInputStream();
int b = -1;
while ( (b = inputStream.read()) != -1 ) {
System.out.write(b);
}
Upvotes: 5
Reputation: 11298
Might be you are getting exception and you've not printed it.
public class ftest2
{
public static void main(String[] arg)
{
System.out.println("NEW FILE PRINT LINE EXECUTED");
try {
Process pro1 = Runtime.getRuntime().exec("javac hworld.java");
pro1.waitFor();
Process pro2 = Runtime.getRuntime().exec("java hworld");
pro2.waitFor();
} catch (Exception e) {
System.out.println("Some Error");
e.printStackTrace();
}
}
}
and another way
public static void main(String[] arg)
{
System.out.println("NEW FILE PRINT LINE EXECUTED");
hworld.main(arg); // since main is a static method can be called w/o instance
}
Upvotes: 0