Gnik
Gnik

Reputation: 7426

How can I run a Ruby script from command line and get the response using Java code?

I need to run the Ruby script using command line from Java code.

For example my file is in the path D:/MyProject/myruby.rb

I want to run this file from command line and get the response from that. How can I achieve this?

Also, how can we return the response in myruby.rb which could be caught in the command line.

Upvotes: 0

Views: 463

Answers (1)

amaurs
amaurs

Reputation: 1642

You can use this:

String[] commands = {"ruby","D:/MyProject/myruby.rb"};

Runtime rt = Runtime.getRuntime();

Process proc;
try
{
    proc = rt.exec(commands);
    BufferedReader stdInput = new BufferedReader(new InputStreamReader(proc.getInputStream()));
    String s;

    while ((s = stdInput.readLine()) != null) 
    {
        System.out.println(s);
    }
}
catch (IOException e)
{
    e.printStackTrace();
}

Upvotes: 1

Related Questions