0

I am wanting to execute this command:

time curl -s 'URL HERE'

In Java and get the results such as:

real    0m0.293s
user    0m0.100s
sys     0m0.052s

What would be the best way to do this?

2 Answers2

2

The general way you execute a command would be to call Runtime.getRuntime().exec(). Runtime.getRuntime().exec() will execute the command you give it. However, there's several caveats:

First, time is a shell built-in command. If you just call

Runtime.getRuntime().exec("time curl -s 'http://www.google.com/'");

then you'll get the following error:

Exception in thread "main" java.io.IOException: Cannot run program "time": error=2, No such file or directory

It looks like you can fix this with sh -c:

Runtime.getRuntime().exec("sh -c \"time curl -s 'http://www.google.com/'\"");

But you can't. exec() splits the string you give it by arguments using a space character without regard to quotes! This is annoying. You can fix that with ProcessBuilder:

Process process = new ProcessBuilder("sh", "-c", "time curl -s 'http://www.google.com/'").start();

This command won't fail, but it also won't appear to do anything! This is because Java doesn't automatically send the output of commands executed to standard out. If you want to do this, you have to manually copy the output:

Process process = new ProcessBuilder("sh", "-c", "time curl -s 'http://www.google.com/'").start();
InputStream in = process.getInputStream();
int i;
while (-1 != (i = in.read())){
    System.out.write(i);
}

This copies the output, but not the error. You can do the same copy procedure with process.getErrorStream() (which returns an InputStream). You could also use redirectErrorStream():

Process process = new ProcessBuilder("sh", "-c", "time curl -s 'http://www.google.com/'").redirectErrorStream(true).start();
InputStream in = process.getInputStream();
int i;
while (-1 != (i = in.read())){
    System.out.write(i);
}

and THAT is how you properly execute the command in Java.

EDIT: You could also download the file in Java natively. In that case, you can use System.nanoTime() to calculate how long it takes.

Leo Izen
  • 4,165
  • 7
  • 37
  • 56
1

You have to use the API Class: ProcessBuilder

Carlitos Way
  • 3,279
  • 20
  • 30