• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to r.exec("java filename");

 
Alexandre Bellezi Jos´┐Ż
Greenhorn
Posts: 16
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
how to run a .class file from Process.exec();.
Running "java filename" command is not working i.e. the .class file dont get executed.Although if i give "javac filename.java" in r.exec(); then the code get executed and the file is compiled
properly.
ANY ANSWERS..
THE CODE FOLLOWS
public class RunTimeTry1
{
public static void main(String [] qq)
{
System.out.println("in the main");
try{
Runtime r;
r = Runtime.getRuntime();
r.exec("java filename");
}catch(Exception e){System.out.println("caught");}
System.out.println("out of the main");}
}
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I ran a test on this as follows.
import java.io.*;
public class run{
public static void main(String args[])
{
try
{
String writeLine = "Testing";
System.out.println(writeLine);
File writeFile =
new File("c:\\java","test.txt");
DataOutputStream dataFile =
new DataOutputStream(new BufferedOutputStream(new
FileOutputStream(writeFile)));
dataFile.write((writeLine.getBytes()));
dataFile.close();
}
catch(IOException ioe)
{System.out.println("Exception : " + ioe);}
}
}
public class runtest
{
public static void main(String [] qq)
{
System.out.println("in the main");
try{
Runtime r;
r = Runtime.getRuntime();
r.exec("java run");
}catch(Exception e){System.out.println("caught");}
System.out.println("out of the main");}
}
And while the System.out.println doesn't display to the console, the file test.txt is created. Therefore I assume that the program did run but, the output is directed to a stream that you can't see. If you need the output from filename to be displayed, you could save it in a file and read it in the original program.
 
Carl Trusiak
Sheriff
Posts: 3341
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I did a little more research and found that you can get the output from the Program run by the exec method using the getInputStream method of java.lang.Process. The new runtest.java is as follows
import java.io.*;
public class runtest
{
public static void main(String [] qq)
{
System.out.println("in the main");
try{
Runtime r;
r = Runtime.getRuntime();
Process p = r.exec("java run");
BufferedReader reader = new BufferedReader(new InputStreamReader(new DataInputStream( new
BufferedInputStream(p.getInputStream()))));
String lineRead =null;
while( (lineRead = reader.readLine() ) != null) {
System.out.println("Input :"+ lineRead+ "\n");
}

}catch(Exception e){System.out.println("caught");}
System.out.println("out of the main");}
}
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic