How to use "cd" command using Java runtime?
Asked Answered
B

8

61

I've created a standalone java application in which I'm trying to change the directory using the "cd" command in Ubuntu 10.04 terminal. I've used the following code.

String[] command = new String[]{"cd",path};
Process child = Runtime.getRuntime().exec(command, null);

But the above code gives the following error

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

Can anyone please tell me how to implement it?

Basilisk answered 3/2, 2011 at 10:2 Comment(1)
An escape was to start a new shell and fire all your commands their - webmasterworld.com/linux/3613813.htmBiphenyl
C
69

There is no executable called cd, because it can't be implemented in a separate process.

The problem is that each process has its own current working directory and implementing cd as a separate process would only ever change that processes current working directory.

In a Java program you can't change your current working directory and you shouldn't need to. Simply use absolute file paths.

The one case where the current working directory matters is executing an external process (using ProcessBuilder or Runtime.exec()). In those cases you can specify the working directory to use for the newly started process explicitly (ProcessBuilder.directory() and the three-argument Runtime.exec() respectively).

Note: the current working directory can be read from the system property user.dir. You might feel tempted to set that system property. Note that doing so will lead to very bad inconsistencies, because it's not meant to be writable.

Cardoso answered 3/2, 2011 at 10:5 Comment(7)
I'm using runtime.exec(). Can you tell me how to specify the working directory explicitly?Basilisk
@Antro #545019Pellitory
@Jigar I already saw that question before. But the solution uses Executer but i want to use Runtime only.Basilisk
use Runtime.getRuntime.exec("cmd /c cd path"); it will workNorvun
Works thanks @DheerajSachan Runtime r = Runtime.getRuntime(); r.exec("cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"); While using array command did NOT WORK String[] cmd = {"cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"}; r.exec(cmd);Lingerie
@Lingerie my answer is below few answers give an up so that it comes up eventually.Norvun
@JoachimSauer: "You shouldn't need to": WRONG. NEVER ASSUME what someone else's code needs, unless you are the provider of a non-standard feature. Even then, you may be wrong, but you are not free to change the standard, that's why they are called standards. Change Directory is a standard disk operating system feature. The fact that you cannot change the current directory disables effective usage of Java's File Object within shell-like-programs and script interpreters. See this postDoelling
D
24

See the link below (this explains how to do it):

http://alvinalexander.com/java/edu/pj/pj010016

i.e. :

String[] cmd = { "/bin/sh", "-c", "cd /var; ls -l" };
Process p = Runtime.getRuntime().exec(cmd);
Deficiency answered 14/1, 2014 at 17:44 Comment(1)
I was just missing the "/bin/sh", "-c" from my command.Buckram
B
14

Have you explored this exec command for a java Runtime, Create a file object with the path you want to "cd" to and then input it as a third parameter for the exec method.

public Process exec(String command,
                String[] envp,
                File dir)
         throws IOException

Executes the specified string command in a separate process with the specified environment and working directory.

This is a convenience method. An invocation of the form exec(command, envp, dir) behaves in exactly the same way as the invocation exec(cmdarray, envp, dir), where cmdarray is an array of all the tokens in command.

More precisely, the command string is broken into tokens using a StringTokenizer created by the call new StringTokenizer(command) with no further modification of the character categories. The tokens produced by the tokenizer are then placed in the new string array cmdarray, in the same order.

Parameters:
    command - a specified system command.
    envp - array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.
    dir - the working directory of the subprocess, or null if the subprocess should inherit the working directory of the current process. 
Returns:
    A new Process object for managing the subprocess 
Throws:
    SecurityException - If a security manager exists and its checkExec method doesn't allow creation of the subprocess 
    IOException - If an I/O error occurs 
    NullPointerException - If command is null, or one of the elements of envp is null 
    IllegalArgumentException - If command is empty
Baby answered 18/7, 2014 at 7:24 Comment(2)
This should the answer I thinkTaxeme
Yes, this is the answer that worked for me: However, keep in mind that the File dir parameter needs to be specified with the last slash included. E.g.: File dir = new File("C:\\l\\workspace\\myproject\\mydirectory\\");Isobaric
A
6

This command works just fine

Runtime.getRuntime().exec(sh -c 'cd /path/to/dir && ProgToExecute)
Acreinch answered 4/4, 2015 at 17:47 Comment(1)
I don't follow shouldn't it be Runtime.getRuntime().exec("sh -c 'cd /path/to/dir && ProgToExecute'")? This returns exit code 2Covet
W
3

Using one of the process builder's method we could pass the directory where we expect the cmd to be executed. Please see the below example. Also , you can mention the timeout for the process, using wait for method.

ProcessBuilder builder = new ProcessBuilder("cmd.exe", "/c", cmd).directory(new File(path));

        Process p = builder.start();

        p.waitFor(timeoutSec, TimeUnit.SECONDS);

In the above code, you can pass the file object of the path[where we expect the cmd to be executed] to the directory method of ProcessBuilder

Whaler answered 10/11, 2018 at 21:59 Comment(0)
M
3

My preferred solution for this is to pass in the directory that the Runtime process will run in. I would create a little method like follows: -

    public static String cmd(File dir, String command) {
        System.out.println("> " + command);   // better to use e.g. Slf4j
        System.out.println();        
        try {
            Process p = Runtime.getRuntime().exec(command, null, dir);
            String result = IOUtils.toString(p.getInputStream(), Charset.defaultCharset());
            String error = IOUtils.toString(p.getErrorStream(), Charset.defaultCharset());
            if (error != null && !error.isEmpty()) {  // throw exception if error stream
                throw new RuntimeException(error);
            }
            System.out.println(result);   // better to use e.g. Slf4j
            return result;                // return result for optional additional processing
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

Note that this uses the Apache Commons IO library i.e. add to pom.xml

   <dependency>
       <groupId>commons-io</groupId>
       <artifactId>commons-io</artifactId>
       <version>2.10.0</version>
   </dependency>

To use the cmd method e.g.

public static void main(String[] args) throws Exception {
    File dir = new File("/Users/bob/code/test-repo");
    cmd(dir, "git status");
    cmd(dir, "git pull");
}

This will output something like this: -

> git status

On branch main
Your branch is up to date with 'origin/master'.

nothing to commit, working tree clean

> git pull

Already up to date.
Multiform answered 28/6, 2021 at 15:32 Comment(0)
N
1

Try Use:

Runtime.getRuntime.exec("cmd /c cd path"); 

This worked

Runtime r = Runtime.getRuntime(); 
r.exec("cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"); 

The below did not work While using array command did NOT WORK

String[] cmd = {"cmd /c pdftk C:\\tmp\\trashhtml_to_pdf\\b.pdf C:\\tmp\\trashhtml_to_pdf\\a.pdf cat output C:\\tmp\\trashhtml_to_pdf\\d.pdf"}; r.exec(cmd);

FYI am using utility to check OS if its windows above will work for other than windows remove cmd and /c

Norvun answered 5/4, 2017 at 16:28 Comment(0)
E
0

I had solved this by having the Java application execute a sh script which was in the same directory and then in the sh script had done the "cd".

It was required that I do a "cd" to a specific directory so the target application could work properly.

Ern answered 3/5, 2017 at 19:19 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.