compiling java file from another java class -
import java.io.bufferedreader; import java.io.inputstreamreader; public class executeshellcomand { public static void main(string[] args) { executeshellcomand obj = new executeshellcomand(); string classname = "str.java"; string command = "javac " + classname; string output = obj.executecommand(command); system.out.println(output);// prints output of executed command } private string executecommand(string command) { stringbuffer output = new stringbuffer(); process p; try { p = runtime.getruntime().exec(command); 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(); } return output.tostring(); } }
i trying compile java file (str.java) java class(executeshellcomand.java). trying if "str.java" compiles want execute "java str" command, if compilation fails proper stacktrace or errors should printed. storing stacktrace or errors in output
variable.
but when execute code although "str.java" has somes errors in system.out.println(output)
not printing errors.
if want capture errors command shall capture error stream instead of input stream
so replace
bufferedreader reader = new bufferedreader(new inputstreamreader(p.getinputstream()));
with
bufferedreader reader = new bufferedreader(new inputstreamreader(p.geterrorstream()));
Comments
Post a Comment