Run compiled Java code at run time

I want to run the previously compiled code It doesn't matter if I compile anyway, but running code is a problem

My code java

public class code{

    public static void main(String[] args) {
        System.out.println("Hello,World");
    }
}

Then I compiled the code and generated code Class (in the D: / / directory) 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 are no errors here, but this code does nothing No CMD open, No What's wrong with me? What should I do?

Solution

Your CMD command is currently incorrect

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

It should be

cmd /c java -cp D:/ code

When you run in another folder Class file but not in the current folder, use - CP to specify the class path

There is actually no error nope But you didn't catch them To catch errors, you can use geterrorstream()

Sample 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();
        }
    }
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>