I am writing a program that utilizes a third party mathematics software, "Maxima". This program is a command line interface, and so it can communicate through my Java program with simple I/O routing. I have already figured out how to run the program from within Java, and I have read a lot about how I can reconfigure System.out and how InputStreams/OutputStreams work, but I can't figure out how to do the following (what I think should be a pretty simple task):
Output to Maxima a command from Java, (like the string "5 + 5;")
Retrieve Maxima's output, and deal with it from Java code (like maybe printing the given string + "blah").
Output another command to Maxima from Java...
etc.
-
Below is code which will run Maxima and allow me to interact with it on the Eclipse Console
public static void main(final String[] args) {
// An idea I had for manipulaing how the printstream works.
// Set the system.out to be a custom Prinstream.
// final PrintStream interceptor = new Interceptor(origOut);
// System.setOut(interceptor);
// Run the program:
final String programLocation = "\"C:\\Program Files (x86)\\Maxima-sbcl-5.37.2\\bin\\maxima.bat\"";
final ProcessBuilder pb = new ProcessBuilder();
pb.redirectInput(Redirect.INHERIT); // Inherit I/O
pb.redirectOutput(Redirect.INHERIT);
pb.command(programLocation);
try {
// Start the program and allow it to run in Eclipse's/the program's
// console.
pb.start().waitFor();
} catch (final InterruptedException e) {
e.printStackTrace();
} catch (final IOException e) {
e.printStackTrace();
}
}
This allows for the following style of interaction:
Thanks to the words of wisdom from #RealSkeptic, I think I worked out a solution here.
The key was building a BufferedWriter, and a BufferedReader to interact with the I/O of Maxima. That is:
BufferedWriter w = new BufferedWriter(new OutputStreamWriter(process.getOutputStream()));
BufferedReader r = new BufferedReader(new InputStreamReader(process.getInputStream()));
Those two lines of code create buffered readers and writers which can input data to Maxima, and read what Maxima output. Here is a (fairly lengthy) use case of this method, which I use to do basically what I asked in the question:
public class TestClass {
public static void main(final String[] args) {
#SuppressWarnings("unused")
final TestClass ts = new TestClass();
}
private BufferedWriter w;
private BufferedReader r;
public TestClass() {
// Start the process using process builder
final String programLocation = "\"C:\\Program Files (x86)\\Maxima-sbcl-5.37.2\\bin\\maxima.bat\"";
final ProcessBuilder pb = new ProcessBuilder();
pb.command(programLocation);
Process process;
try {
process = pb.start();
} catch (final IOException e) {
e.printStackTrace();
process = null;
// killProgram();
}
// Build your own wrappers for communicating with the program.
w = new BufferedWriter(
new OutputStreamWriter(process.getOutputStream()));
r = new BufferedReader(new InputStreamReader(process.getInputStream()));
// Print the five starting messages.
printFromBuffer();
printFromBuffer();
printFromBuffer();
printFromBuffer();
printFromBuffer();
// Run the following three commands in Maxima
runCommand("5+5;");
runCommand("2*65;");
runCommand("quit();");
}
/**
* Runs the given string and prints out the returned answer.
*/
private void runCommand(final String s) {
try {
w.write(s);
w.flush();
printFromBuffer();
printFromBuffer();
} catch (final IOException e) {
e.printStackTrace();
}
}
private void printFromBuffer() {
try {
final String s = r.readLine();
System.out.println(s + " -blah");
} catch (final IOException e) {
System.err.println(e.getMessage());
e.printStackTrace();
}
}
}
Related
Real Goal: create a program that calls other programs(lab exercises)
Current goal: Make Main.java run Lab4 a GUI program (Lab4Ans201506159.java - the filename)
Lab4Form and Lab4Intro are forms
here is the Main.java code
public class Main {
public static void main(String[] args) throws IOException {
// TODO code application logic here
Process p,p2,p3,p4;
p = Runtime.getRuntime().exec("javac Lab4Ans201506159.java");
//p3 = Runtime.getRuntime().exec("javac Lab4Ans201506159Form.java");
//p4 = Runtime.getRuntime().exec("javac Lab4Ans201506159Intro.java");
p2 = Runtime.getRuntime().exec("java Lab4Ans201506159");
//p2 = Runtime.getRuntime().exec("Lab4Ans201506159");
}
and here is the Lab4 code
Lab4Form and Lab4Intro are Frames
what Lab4 is trying to do displaying Lab4Intro, and when it is closed, Lab4Form would be visible
public class Lab4Ans201506159 {
public static void main(String[] args) throws InterruptedException {
Lab4Ans201506159Intro intro = new Lab4Ans201506159Intro();
intro.setLocationRelativeTo(null);
intro.setVisible(true);
Thread.sleep(2000);
//Lab4Ans201506159Form form = new Lab4Ans201506159Form();
while(intro.isActive())
{
}
if(intro.isActive() == false){
Lab4Ans201506159Form form = new Lab4Ans201506159Form();
form.setLocationRelativeTo(null);
form.setVisible(true);
}
}
Problem: Running Main.java will result to a "BUILD SUCCESSFUL" in the compiler but no GUI is displayed. I need answers why it does not display or work.
I suspect only the first Process is executed, in order to be sure, have you already tried to redirect the output of Runtime.exec to the standard output
something like that:
public static void main(String[] args) throws Exception {
System.setOut(new PrintStream(new FileOutputStream("log.txt")));
System.out.println("Init...");
try {
String line;
Process p = Runtime.getRuntime().exec( "javac Lab4Ans201506159.java" );
BufferedReader in = new BufferedReader(
new InputStreamReader(p.getInputStream()) );
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
}
Thread.sleep(1000);
Process p2 = Runtime.getRuntime().exec("java Lab4Ans201506159" );
BufferedReader in2 = new BufferedReader(
new InputStreamReader(p2.getInputStream()) );
while ((line = in2.readLine()) != null) {
System.out.println(line);
}
in2.close();
}
catch (Throwable e) {
e.printStacktrace();
}
}
like that you can verify what is going wrong...
good luck
I managed to finish my end goal which is to open Lab4. I sort of took a different method though. I suspect one of the reasons why it does not work is because my classpath must have been wrong. I could say that because I can't compile (javac) in CMD Prompt. So I fixed that, then I 'clean and build' (using Netbeans) the project(lab4,intro,form). After that, in the last line of the compiler there will be a line like "java -jar C:\sdfsafs\blablabal". That was the line I used inside runtime.exec() and it finally worked.
public static void main(String[] args) throws Exception {
try {
runProcess("java -jar \"C:\\Users\\Aldrin\\Desktop\\201506159AnsLab4\\dist\\201506159AnsLab4.jar\"");
//runProcess("dir");
//runProcess("java Lab4Ans201506159");
} catch (Exception e) {
e.printStackTrace();
}
}
I still have not answered why the original code does not work though.
This question already has answers here:
run interactive command line application from java
(2 answers)
Closed 6 years ago.
Basically, I have a process which runs when I press a button on my java application.
And this process executes a command to the terminal of the OS.
But sometimes this command needs to have an interaction with the user.
And I would like to know if this was possible to have the interaction from the process to the user when needed?
My code:
File marsSimulator = new File("resources/mars_simulator/Mars4_5.jar");
if(marsSimulator.exists() && temp.exists()){
String res="";
try {
Process p = Runtime.getRuntime().exec(new String[]{"java","-jar",marsSimulator.getAbsolutePath(),tempAssembly.getAbsolutePath()});
p.waitFor();
InputStream is = p.getInputStream();
byte b[] = new byte[is.available()];
is.read(b, 0, b.length); // probably try b.length-1 or -2 to remove "new-line(s)"
res = new String(b);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Also, I forgot to say that the application is made with SWING and that the output of the process is shown onto a TextArea... Should I change anything ?
Notice that the process blocks when there is an interaction with the user. If there isn't, the process doesn't block !
What do I need to do in this case (which I don't know how to do it ) ?
When the process needs the interaction. I need to know when the process wants some interaction.
I need to get the output generated of the process interactively (line by line).
P.S.: For people who wanna understand the process line, I am using the Mars Simulator (http://courses.missouristate.edu/KenVollmar/MARS/) and I am sending the jar application into a process with a mips assembly code associated.
This next pieces of code is working with my project
Hope it will help for the next adventurers!
And thank you to Nicolas Filotto for helping me.
My class ObservableStream:
class ObservableStream extends Observable {
private final Queue<String> lines = new ConcurrentLinkedQueue<>();
public void addLine(String line) {
lines.add(line);
setChanged();
notifyObservers();
}
public String nextLine() {
return lines.poll();
}
public String getLine(){return lines.peek();}
}
And the other part of the code:
Process p = Runtime.getRuntime().exec(new String[]{"java","-jar",marsSimulator.getAbsolutePath(),tempAssembly.getAbsolutePath()});
//This code does the interaction from the process with the GUI ! Implied, input interaction+output interaction from the process
ObservableStream out = new ObservableStream();
// Observer that simply sends to my external process line by line what we put in
// the variable output
PrintWriter writer = new PrintWriter(p.getOutputStream(), true);
out.addObserver(
(o, arg) -> {
ObservableStream stream = (ObservableStream) o;
String line;
while ((line = stream.nextLine()) != null) {
writer.println(line);
}
}
);
ObservableStream input = new ObservableStream();
input.addObserver(
(o, arg) -> {
ObservableStream stream = (ObservableStream) o;
String line;
while ((line = stream.nextLine()) != null) {
outputTextArea.appendText(line+"\n");
}
}
);
// The thread that reads the standard output stream of the external process
// and put the lines into my variable input
new Thread(
() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()))
) {
String line;
while ((line = reader.readLine()) != null) {
input.addLine(line);
}
} catch (IOException e1) {
e1.printStackTrace();
}
}
).start();
new Thread(
()->{
while(p.isAlive()){
String res = input.getLine();
if(res!=null && res.equals("Enter integer value:")) {
boolean integerIsRequested=true;
Thread t=null;
while(integerIsRequested){
if(t==null) {
t = new Thread(new Runnable() {
public void run() {
String test1 = JOptionPane.showInputDialog("Enter Integer value:");
while(!test1.matches("^\\d+$")){
test1 = JOptionPane.showInputDialog("Error: Not a valid Integer.\nEnter a correct Integer value:");
}
Integer i = Integer.valueOf(test1);
if (i != null) {
out.addLine(test1);
}
}
});
t.start();
}
if(!t.isAlive()){
integerIsRequested=false;
}
}
}
}
outputTextArea.appendText("Program executed\n");
}
).start();
By the way, this post is unique Jarrod ;)
To implement such use case I would personally use:
An Observable object to notify my UI when a new line has been provided by the external process
An Observable object to which I add new lines provided by my UI
An Observer of #1 that will refresh the data of my UI
An Observer of #2 that will send the lines provided by my UI to my external process
A Thread that will check if a new line has been provided by my external process and if so it will provide those lines to #1
So as I don't have your full env, I will show you how it will work with mock objects:
First my fake external application that only does an Echo of what he receives:
public class Echo {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
while (true) {
String line = scanner.nextLine();
System.out.printf("echo > %s%n", line);
}
}
}
If this class receives foo, it will print into the standard output stream echo > foo
Then my Observable class
public class ObservableStream extends Observable {
private final Queue<String> lines = new ConcurrentLinkedQueue<>();
public void addLine(String line) {
lines.add(line);
setChanged();
notifyObservers();
}
public String nextLine() {
return lines.poll();
}
}
NB: The class ObservableStream (as it is implemented so far) is meant to have only one Observer no more which is enough according to your needs. Indeed is only used to decouple your UI from how the data is retrieved or published
Then finally the main code:
Process p = Runtime.getRuntime().exec(
new String[]{"java", "-cp", "/my/path/to/my/classes", "Echo"}
);
// The Observable object allowing to get the input lines from my external process
ObservableStream input = new ObservableStream();
// A mock observer that simply prints the lines provided by the external process
// but in your case you will update your text area instead
input.addObserver(
(o, arg) -> {
ObservableStream stream = (ObservableStream) o;
String line;
while ((line = stream.nextLine()) != null) {
System.out.printf("Line Received from the external process: %s%n", line);
}
}
);
// The thread that reads the standard output stream of the external process
// and put the lines into my variable input
new Thread(
() -> {
try (BufferedReader reader = new BufferedReader(
new InputStreamReader(p.getInputStream()))
) {
String line;
while ((line = reader.readLine()) != null) {
input.addLine(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
).start();
// The Observable object allowing to send the input lines to my external process
ObservableStream output = new ObservableStream();
// Observer that simply sends to my external process line by line what we put in
// the variable output
PrintWriter writer = new PrintWriter(p.getOutputStream(), true);
output.addObserver(
(o, arg) -> {
ObservableStream stream = (ObservableStream) o;
String line;
while ((line = stream.nextLine()) != null) {
writer.println(line);
}
}
);
// A simple scanner used to send new messages to my external process
Scanner scanner = new Scanner(System.in);
while (true) {
output.addLine(scanner.nextLine());
}
If this code receives foo, it will print into the standard output stream Line Received from the external process: echo > foo
I hope it answers your question... subProcessStuff "emulates" that sub process. It can be anything - but this way we have all in place. It requires 2 params passed into console. String and Integer. Gobbler got Callback which is an interface, with anonymous implementation - and there are checks for params. To answer if subprocess waits we simply track what is says - just like if a user would operate with it.
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintStream;
import java.util.Scanner;
class Test1 {
public static void main(String[] args) {
for (String arg : args)
System.out.println("arg: " + arg);
for (String arg : args)
if (arg.equals("-test")) {
subProcessStuff();
return;
}
mainProcess();
}
public static void subProcessStuff() {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
try {
System.out.println("Enter String");
String s = br.readLine();
System.out.println("Enered String: " + s);
System.out.println("Enter Integer:");
int i = Integer.parseInt(br.readLine());
System.out.println("Entered Integer: " + i);
} catch (IOException e) {
System.err.println("io error - " + e.getMessage());
} catch (NumberFormatException nfe) {
System.err.println("Invalid Format!");
}
}
private static PrintStream out;
public static void mainProcess() {
String[] commands = { "ls", "-alt" };
ProcessBuilder builder = new ProcessBuilder("java", "Test1", "-test");
// builder.inheritIO(); // I avoid this. It was messing me up.
try {
Process proc = builder.start();
InputStream errStream = proc.getErrorStream();
InputStream inStream = proc.getInputStream();
OutputStream outStream = proc.getOutputStream();
new Thread(new StreamGobbler("err", out, errStream)).start();
out = new PrintStream(new BufferedOutputStream(outStream));
Callback cb = new Callback() {
#Override
public void onNextLine(String line) {
if (line.equals("Enter String")) {
out.println("aaaaa");
out.flush();
}
if (line.equals("Enter Integer:")) {
out.println("123");
out.flush();
}
}
};
new Thread(new StreamGobbler("in", out, inStream, cb)).start();
int errorCode = proc.waitFor();
System.out.println("error code: " + errorCode);
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (out != null) {
out.close();
}
}
}
}
interface Callback {
void onNextLine(String line);
}
class StreamGobbler implements Runnable {
private PrintStream out;
private Scanner inScanner;
private String name;
private Callback cb;
public StreamGobbler(String name, PrintStream out, InputStream inStream) {
this.name = name;
this.out = out;
inScanner = new Scanner(new BufferedInputStream(inStream));
}
public StreamGobbler(String name, PrintStream out, InputStream inStream, Callback cb) {
this.name = name;
this.out = out;
inScanner = new Scanner(new BufferedInputStream(inStream));
this.cb = cb;
}
#Override
public void run() {
while (inScanner.hasNextLine()) {
String line = inScanner.nextLine();
if (cb != null)
cb.onNextLine(line);
System.out.printf("%s: %s%n", name, line);
}
}
}
I don't think you can check the state of the process from the Java. However you can do it by using some Linux command. (Of course if you're using Linux)
If your Java process has access to the /proc directory then you can read the status file for the process.
For example for a process with process id 12280
/proc/12280/status
Here's the relevant output of the status file
Name: java
State: S (sleeping)
Tgid: 12280
Pid: 12280
PPid: 12279
...
Second line gives the state of the process. You'll need to run a thread to continuously poll this file to read the status.
Line by Line The Code i use to interract with a different jar which is a speechRecognizer.I think you want to achieve something like this.
Example:
The jar i am interracting(speechRecognizer) is executing different commands and run some other Threads.Every time it has to interract with the main jar it prints something that i need.For example (user said:How are you),so you can have a same logic and when external jar need interraction with user it prints something and you read it into the main app.So:
// About Process
private Process process;
private BufferedReader bufferedReader;
private boolean stopped = true;
Thread processChecker;
//Running it in a Thread so the app don't lags
new Thread(() -> {
try {
stopped = false;
//Starting the external jar..
ProcessBuilder builder = new ProcessBuilder("java", "-jar", System.getProperty("user.home")
+ File.separator + "Desktop" + File.separator + "speechRecognizer.jar", "BITCH_PLEASE");
//Redirecting the ErrorStream
builder.redirectErrorStream(true);
process = builder.start();
bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
//Check continusly if the process is still alive
//i case of crash i should do something..
processChecker = new Thread(() -> {
while (process.isAlive()) {
try {
Thread.sleep(1200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
stopSpeechReader(false);
});
processChecker.start();
// Continuesly Read Output of external process
while (!stopped) {
while ((line = bufferedReader.readLine()) != null && !line.isEmpty()) {
System.out.println(line);
checkSpeechResult(line);
}
}
// Interrupt the mf Thread if is Alive
if (processChecker.isAlive())
processChecker.interrupt();
System.out.println("SpeechReader Stopped! Process is alive:" + process.isAlive() + " >Exit Value:"
+ process.exitValue());
} catch (Exception e) {
e.printStackTrace();
}
}).start();
I want a java program to execute the following shell command:
apktool.jar d /path/to/my/app.apk
This command perfectly works when executing it directly on command line.
Java Code:
public static void main(String[] args) {
String command = "apktool d /path/to/my/app.apk";
try {
Runtime.getRuntime().exec(command);
} catch (IOException e1) {
e1.printStackTrace();
}
}
There is no error, no exception. Nothing happens and i have the impression that I already searched the entire internet for a solution. Does anybody know what I am doing wrong? A simple command like
mkdir /path/to/a/new/folder
works without problems.
I tried the same using ProcessBuilder:
try {
Process process = new ProcessBuilder(command).start();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This time i only get "Cannot run program "apktool d /path/to/my/app.apk, No such file or directory". I can't even run the mkdir command.
You need to call the jar with java.exe, and you're not doing that. Also you need to trap the input and error streams from the process, something you can't do the way you're running this. Use ProcessBuilder instead, get your streams and then run the process.
For example (and I can only do a Windows example),
import java.io.IOException;
import java.io.InputStream;
import java.util.Scanner;
public class ProcessEg {
private static Process p;
public static void main(String[] args) {
String[] commands = {"cmd", "/c", "dir"};
ProcessBuilder pBuilder = new ProcessBuilder(commands);
pBuilder.redirectErrorStream();
try {
p = pBuilder.start();
InputStream in = p.getInputStream();
final Scanner scanner = new Scanner(in);
new Thread(new Runnable() {
public void run() {
while (scanner.hasNextLine()) {
System.out.println(scanner.nextLine());
}
scanner.close();
}
}).start();
} catch (IOException e) {
e.printStackTrace();
}
try {
int result = p.waitFor();
p.destroy();
System.out.println("exit result: " + result);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
Try doing it like this:
StringBuffer output = new StringBuffer();
Process p;
try {
p = Runtime.getRuntime().exec("./path/apktool d /path/to/my/app.apk");
p.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = "";
while ((line = reader.readLine())!= null) {
output.append(line + "\n");
}
} catch (Exception e) {
e.printStackTrace();
}
system.out.println(output.toString());
Creating first a process allows you to wait for a response and reads the output of the execution of your process.
If something is failing while running your shell command, you will have the error printed at the end.
Also, make sure your java program can access your shell script, or better provide the full path to it like:
./path/to/shell/apktool d /path/to/my/app.apk
I'm working on a project and I would like to execute programs in the windows console or a linux terminal.
Instead of launching a new console and working the program in it I want to do something like the following:
rt.exec("cmd.exe /c start cmd.exe /k ruby rubycode.rb");
From this point on I want the user to be able to work with the program from the GUI/my program. The idea in my min is starting cmd in silent mode where it is not visible and latching on to it. Then redirecting the console output to the GUI and letting the user input data to the console through the GUI.
A similar concept is what most IDEs like jgrasp do. When you run a program you interface with it though their own command prompt.
How is this done? Iv'e tried grabbing the IOStreams from the process and trying to atleast print what the console outputs but no luck.
Here is an example:
public class ProcessTest {
private Process p;
private BufferedReader reader;
private BufferedWriter writer;
public void start() throws IOException {
ProcessBuilder pb = new ProcessBuilder("cmd", "/c", "dir");
pb.directory(new File("./"));
this.p = pb.start();
this.reader = new BufferedReader(new InputStreamReader(this.p.getInputStream()));
this.writer = new BufferedWriter(new OutputStreamWriter(this.p.getOutputStream()));
new Read(this.reader).start();
}
public boolean writeToConsole(String s) throws IOException {
if (p == null)
return false;
this.writer.write(s + "\n");
this.writer.flush();
return true;
}
public class Read extends Thread {
private BufferedReader reader;
public Read(BufferedReader reader) {
this.reader = reader;
}
public void run() {
try {
String line;
while ((line = this.reader.readLine()) != null) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
try {
new ProcessTest().start();
} catch (IOException e) {
e.printStackTrace();
}
}
}
With the writeToConsole method you can write any string to the programm that you executed.
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.
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);
}
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.
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
}