Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running compiled java code at runtime

Tags:

java

cmd

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?

like image 271
Gürkan Çatak Avatar asked Jul 15 '15 10:07

Gürkan Çatak


1 Answers

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();
        }
    }
}
like image 71
Madhawa Priyashantha Avatar answered Oct 03 '22 21:10

Madhawa Priyashantha