Running bash cmds within Java

Viewed 30

I'm trying to run a bash cmd that grabs infomation from the google api using my api key. I run the code in the terminal and I get the output that I want (which is the address alone). But when I try use the call within java it doesnt work. I believe it ends up being a null call.

The cmd is as follows: "wget -O- -q "https://maps.google.com/maps/api/geocode/json?address=4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan&key=[MY_API_KEY]"|grep '"formatted_address"'|cut -d\: -f2

This is my current java code

public static void main(String[] args) throws Exception {
    Process runtime = Runtime.getRuntime().exec("wget -O- -q \"https://maps.google.com/maps/api/geocode/json?address=4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan&key=[MY_API_KEY]\"|grep '\"formatted_address\"'|cut -d\\: -f2");
    Show_Output(runtime);
}
public static void Show_Output(Process process) throws IOException {
    BufferedReader output_reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String output = "";
    while ((output = output_reader.readLine()) != null) {
        System.out.println(output);
    }
    System.out.println(output);
}

Desired output is: "4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan",

1 Answers

With the Process class you can only execute a single command. You on the other hand have 3:

  • wget -O- -q "https://maps.google.com/maps/api/geocode/json?address=4-chōme-2-8 Shibakōen, Minato City, Tokyo 105-0011, Japan&key=[MY_API_KEY]"
  • grep '"formatted_address"'
  • cut -d: -f2

I see 4 options:

  1. create a shell script that contains these commands, and execute that
  2. create 3 processes (one for each command), and chain their input / output streams.
  3. use a process only for the curl command, and perform the grep and cut in Java
  4. skip using commands completely, and just use Java for the entire thing

I'd personally go for option 4. With Java's own HttpClient this should be pretty straight forward.

  • use HttpClient to get the response as a string
  • use response.lines() to get a stream of lines
  • use filter to replace grep (.filter(line -> line.contains("...")))
  • use string manipulation to replace cut
Related