Search code examples
javaterminalruntimeprocessbuilder

Open terminal in a specific folder


String command= "/usr/bin/xterm"; 
Runtime rt = Runtime.getRuntime();  
Process pr = rt.exec(command);

Using the code above I managed to open terminal using java, but the "problem" is that the terminal opens in the folder where my java project is located. How can I open the terminal AND redirect it automatically to a specific folder e.g I want that the terminal gets opened in the Download folder.


Solution

  • Another way of doing it is to pass your working directory as a File to the Runtime's exec method with the following signature:

    exec(String command, String[] envp, File dir)
    // Executes the specified string command in a separate process with the 
    // specified environment and working directory.
    

    Something like this:

    String command = "/usr/bin/xterm"; 
    File workDir = new File("/home/Download");
    Runtime rt = Runtime.getRuntime();
    Process pr = rt.exec(command, null, workDir);