Running compiled java code at runtime

I want to run code compiled earlier. In any case, I compiled, no matter how to compile, but running the code is a 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(); } } } 

There is no error here, but this code does nothing. No cmd opened, nothing. Where am I mistaken? What should I do?

+7
java cmd runtime
source share
1 answer

Your cmd command is currently invalid.

 cmd /c java code D:/ /*this is not correct cmd command*/ 

he should be

 cmd /c java -cp D:/ code 

when you run the .class file in another folder, but not in the current folder, use -cp to specify the class path

there is no error There really wasn’t. but you didn’t capture them. To capture errors you can use getErrorStream()

code example

 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(); } } } 
+4
source share

All Articles