invoking javac with Runtime.exec(...)
2 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Florian_Kummer
Posted On:   Monday, August 26, 2002 07:16 AM

Hello;

I want to invoke the javac Compiler from within a running java application:

			

Process javac = Runtime.getRuntime().exec ( "javac tst.java");
javac.waitFor(); // causes the current thread to wait until javac is finished



My problem is that the waitFor() - Method never returns;
When I start the Notepad - Editor in a simmilar way, it works in the expected way and blocks until I close Notepad;

But why it dosnt't work with javac or fastjavac ?

Re: invoking javac with Runtime.exec(...)

Posted By:   Axel_Richter  
Posted On:   Wednesday, August 28, 2002 11:26 PM

Your problem is not waitFor(). The process Runtime.getRuntime().exec ("javac tst.java"); hangs, because it wants to write something to stdout or stderr. You have to create Streams for this.



This works with me:


class FileCompileAction extends AbstractAction {
public FileCompileAction() {
super("Compile");
}

public void actionPerformed(ActionEvent e) {

String cmd1 = "Javac";
String cmd2 = "";
String fName = "Main.java";
File dir = new File("D:\");

String[] cmdarray = {cmd1, cmd2, fName};
String[] env = {};

try {
Process p = Runtime.getRuntime().exec(cmdarray, env, dir);
BufferedInputStream err = new BufferedInputStream(p.getErrorStream());
BufferedInputStream out = new BufferedInputStream(p.getInputStream());
String cerr = "";
String cout = "";
Character c;
int i = -1;
while((i = err.read()) != -1) {
c = new Character((char)i);
cerr = cerr.concat(c.toString());
}
err.close();

i = -1;
while((i = out.read()) != -1) {
c = new Character((char)i);
cout = cout.concat(c.toString());
}
out.close();

int stat = 0;
try {
stat = p.waitFor();
} catch (InterruptedException ie) {
ie.printStackTrace();
}

p.destroy();

System.out.println("Ende mit: "+stat);
System.out.println(cout);
System.out.println(cerr);
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
}

Re: invoking javac with Runtime.exec(...)

Posted By:   Anonymous  
Posted On:   Tuesday, August 27, 2002 02:42 AM

You java compiler must be in the path if you want this code to work, otherwise you need to specify full path.
About | Sitemap | Contact