Using Runtime.getRuntime().exec in eclipse

北慕城南 提交于 2019-12-04 17:10:40
prunge

You need to read the output (and error) streams from the Process using getInputStream() and getErrorStream(). You’ll need a separate thread for this if you want to wait for the process to complete.

String[] cmd = {"java", "-cp", "C:/Users/..../workspace/Testing/bin", s, str};
Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
final InputStream pOut = p.getInputStream();
Thread outputDrainer = new Thread()
{
    public void run()
    {
        try
        {
            int c;
            do
            {
                c = pOut.read();
                if (c >= 0)
                    System.out.print((char)c);
            }
            while (c >= 0);
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
    }
};
outputDrainer.start();

p.waitFor();

If you are using Java 7 and want all output of the process to be redirected to the console, the code is considerably simpler:

String[] cmd = {"java", "-cp", "C:/Users/..../workspace/Testing/bin", s, str};
Process p = new ProcessBuilder(cmd).redirectError(Redirect.INHERIT)
                                   .redirectOutput(Redirect.INHERIT)
                                   .start();
p.waitFor();

The redirectError() and redirectOutput() methods with Redirect.INHERIT cause output to just be sent to the parent Java process.

You are executing javac, the language compiler. I believe you want to invoke the java runtime on the class file with your main method. Replace javac with java, and specify your main class.

You are passing your data as an Argument but reading it from System.in. If you read the data from the arguments it'll work. So do what @prunge said to capture what the subprocess print and use this as your test and everything will work just fine.

import java.io.*;
public class Test
{
    public static void main(String[] args) throws IOException
    {   
        if(args.length==0)
            System.out.println("No String received");
        else
            System.out.println("Your string is " + args[0]);    
    }
}

Be sure that you check both the InputStream and the ErrorStream.

If you however want to pass the data via System.in then you have to change your call code to:

InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br=new BufferedReader(isr);
System.out.println("Enter the class name");
String s=br.readLine();    
String str="XYZ";
String[] cmd = {"java","-cp", "C:/Users/..../workspace/Testing/bin",s};         
Process pro=Runtime.getRuntime().exec(cmd);
PrintWriter output= new PrintWriter(pro.getOutputStream());
output.println(str);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!