Search code examples
javaprocessbuilderruntime.exec

How can I use either Runtime.exec() or ProcessBuilder to open google chrome through its pathname?


I am writing a java code that has the purpose of opening a URL on youtube using Google Chrome but I have been unsuccessful in understanding either method. Here is my current attempt at it.

import java.lang.ProcessBuilder;
import java.util.ArrayList;
public class processTest
{
    public static void main(String[] args)
    {
    ArrayList<String> commands = new ArrayList<>();
    commands.add("cd C:/Program Files/Google/Chrome/Application");
    commands.add("chrome.exe youtube.com");
    ProcessBuilder executeCommands = new ProcessBuilder( "C:/WINDOWS/System32/WindowsPowerShell/v1.0/powershell.exe", "cd C:/Program Files/Google/Chrome/Application", "chrome.exe youtube.com");
    }
}

It compiles OK, but nothing happens when I run it. What is the deal?


Solution

  • As stated by Jim Garrison, ProcessBuilder's constructor only executes a single command. And you do not need to navigate through the directories to reach the executable.

    Two possible solutions for your problem (Valid for my Windows 7, be sure to replace your Chrome path if neccesary)

    With ProcessBuilder using constructor with two parameters: command, argument (to be passed to command)

        try {
            ProcessBuilder pb =
               new ProcessBuilder(
                  "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", 
                  "youtube.com");
    
            pb.start();
    
            System.out.println("Google Chrome launched!");
        } catch (IOException e) {
            e.printStackTrace();
        }
    

    With Runtime using method exec with one parameter, a String array. First element is the command, following elements are used as arguments for such command.

        try {
            Runtime.getRuntime().exec(
              new String[]{"C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe", 
                           "youtube.com"});
    
            System.out.println("Google Chrome launched!");
        } catch (Exception e) {
            e.printStackTrace();
        }