0

Hi guys :) I'm actually working on a project and i have to execute a class in a new command prompt, but i have to do it using java. So in a specific class Class, i have to write the right code which call the class Sensor in a new command prompt. i have this code lines which opens a new command prompt but how to make it execute the class Sensor on that command prompt opened ?

 String[] command =(new String[]{"cmd", "/k", "start", "cmd" , "\""});
  Runtime.getRuntime().exec(command);

Any help would be appreciated!! Thanks in advance :)

Anja.M
  • 23
  • 1
  • 7
  • Can you please show us your Sensor class? – timothyclifford Jul 03 '16 at 09:56
  • @timothyclifford It's a bit complicate but something like : (It's not complete) public class Sensor{ public static void main(String[] args) throws IOException, JSONException { do { // MAKES A REST POST REQUEST TO A SERVER REST // RECEIVES THE RESPONSE Sensor.simulation(type, idnumber); // ACTIVATE THE SENSOR sensors.Sensor.tokenManagement(prevPort,nextId,nextPort);// MANAGE THE TOKEN} System.out.println("Push exit to delete the sensor");{ //DELETE REQUEST TO SERVER REST }//RESPONSE FROM SERVER, {System.exit(1);} – Anja.M Jul 03 '16 at 10:09
  • Please take a look on [Output from command prompt returning null](http://stackoverflow.com/questions/38113931/) to understand what `cmd /c start cmd.exe /K` or other variants like above `cmd /k start cmd` mean which looks like many Java programmers use without knowing what happens here. – Mofi Jul 04 '16 at 17:56

1 Answers1

0

Try this code
it will open cmd and execute the command passed to it
To Compile the java file.

String command="cmd /c \""+drive+" && cd "+fileParentDrive+" && javac "+javaFileName+"\"";
Process child = Runtime.getRuntime().exec(command);

To run class file

command="cmd.exe /k start cmd.exe /k \""+drive+" && java "+classFileName+"\"";
child = Runtime.getRuntime().exec(command , null , new File(drive+ parent));

Method Runtime.getRuntime().exec(command) will return the reference of Process Class. now you can get the output of the file while executing on cmd as follow

To get errors if occurs at compile time

InputStream in = child.getErrorStream();
int i;
String error="";
while((i=in.read())!=-1)
{
    error+=(char)i;
}
Sharad Gautam
  • 91
  • 5
  • 11