简体   繁体   中英

Execute a program that prints “hello world” from another program in java

I initially wrote program named "Command.java" that compiles another program named "New.java" which in turn prints hello world to the console.But the after executing Command.java , I found that it successfully compiled "New.java" but didn't print "Hello world" in the console.Here are the codes :-

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

}

import java.io.*;
class Command 
{
    public static void main(String[]args)throws IOException
    {


        Runtime r=Runtime.getRuntime();
        try
        {


            Process p=r.exec("cmd pushd C:\\Users\\Admin\\Desktop");

            p=r.exec("\"E:\\jdk1.7.0_11\\bin\\javac.exe\" New.java");
            p.waitFor();
            p=r.exec("\"E:\\jdk1.7.0_11\\bin\\java.exe\" New"); 
            p.waitFor();

    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
}

}

But after making some changes in the Command.java it worked.....and here is the new Command.java code:-

import java.io.*;
class Command 
{
    public static void main(String[]args)throws IOException
    {


        Runtime r=Runtime.getRuntime();
        try
        {


            Process p=r.exec("cmd pushd C:\\Users\\Admin\\Desktop");

            p=r.exec("\"E:\\jdk1.7.0_11\\bin\\javac.exe\" New.java");
            p.waitFor();
            p=r.exec("\"E:\\jdk1.7.0_11\\bin\\java.exe\" New"); 
            p.waitFor();
            InputStream in= p.getInputStream();
            BufferedReader br=new BufferedReader(new InputStreamReader(in));
            System.out.println(br.readLine());
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
}

}

Now my question is why my previous Command.java program didn't print Hello world but my second version worked.

您需要从Java程序中读取系统命令的输出。因此,您编写的第一个程序没有显示输出。由于您读取了输出,因此第二个程序运行良好

Each java application runs in it's own console. The console you see when launching your program belongs to Command.java. This means it will only show output from Command.java and nothing else. New.java runs in a different console that in this case is not shown to you. The second version of Command.java reads the output from New.java and then prints it to it's own console.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM