Running compiled java code at runtime
I want to run code compiled before. I compiled anyway it is not important how to compile but running the code is problem.
My code.java
public class code{
public static void main(String[] args) {
System.out.println("Hello, World");
}
}
Then I compiled this code and code.class
(in the D://
directory) was generated. Now I want to run this compiled file. My code is :
import java.io.IOException;
import java.io.InputStream;
public class compiler {
public static void main(String[] args) {
final String dosCommand = "cmd /c java code";
final String location = "D:";
try {
final Process process = Runtime.getRuntime().exec(
dosCommand + " " + location);
final InputStream in = process.getInputStream();
int ch;
while((ch = in.read()) != -1) {
System.out.print((char)ch);
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Here there is no error but this code does not do anything. No cmd opened, nothing. Where am I wrong? What should I do?
current your cmd
command is wrong.
cmd /c java code D:/ /*this is not correct cmd command*/
it should be
cmd /c java -cp D:/ code
when you run a .class file in a different folder but not in current folder use -cp
to specifies the class path
there is no error
nope actually there was .but you didn't capture them .to capture errors you can use getErrorStream()
example code
public class compiler {
public static void main(String[] args) {
final String dosCommand = "cmd /c java -cp ";
final String classname = "code";
final String location = "D:";
try {
final Process process = Runtime.getRuntime().exec(dosCommand + location + " " + classname);
final InputStream in = process.getInputStream();
final InputStream in2 = process.getErrorStream();
int ch, ch2;
while ((ch = in.read()) != -1) {
System.out.print((char) ch);
}
while ((ch2 = in2.read()) != -1) {
System.out.print((char) ch2); // read error here
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
链接地址: http://www.djcxy.com/p/86660.html
上一篇: 两种类型的用户在一个注册表中注册?
下一篇: 在运行时运行编译的Java代码