1

I want to execute an array of commands in my dir. When I hit cd C:/Users/Lennart/sciebo/Semster 2/Info/RepoCreator/Abgabe 4 into the command line it works fine. But when I execute the follwing code I am getting a FileNotFoundException, because "System cannot find the file specified".

    Runtime.getRuntime().exec(getCMDs());

    ...

    private static String[] getCMDs() {
        String cd = "cd C:/Users/Lennart/sciebo/Semster 2/Info/RepoCreator/Abgabe " + index;
//      String cd = "cd " + path + "/Abgabe " + index;
        String init = "git init";
        String add = "git add .";
        String commit = "git commit -m \"Inital commit\"";

        return new String[] {cd, init, add, commit};
    }

I tried to use Runtime.getRuntime().exec(getCMDs(), null, file) with the required changes. File was File file = new File("C:/Users/Lennart/sciebo/Semster 2/Info/RepoCreator/Abgabe 4"); Loading the file was not a problem and also System.out.println(file.exists()); was true, but executing the array led to the same error.

Thank you

EDIT:

Yes, I tried the overloaded methode as described above. Here is the code:

File file = new File(path + "/RepoCreator/Abgabe 4");
        System.out.println(file.exists());
        try {
            Runtime.getRuntime().exec(getCMDs(), null, file);
...

    private static String[] getCMDs() {
        String init = "git init";
        String add = "git add .";
        String commit = "git commit -m \"Inital commit\"";

        return new String[] {init, add, commit};
    }

Unfortunally this does not make a difference.

longroad
  • 87
  • 6

3 Answers3

1

It looks like you are trying to execute git commands in the specified directory.

You can try using an overloaded version of the exec method:

public Process exec(String[] cmdarray,
           String[] envp,
           File dir)

Here is an example on SO (snippet below)

Process process2=Runtime.getRuntime().exec("myfile",
    null, new File("/data/data/my-package/files"));

Edit: In your getCMDs() omit the cd command again when using this exec() method.

return new String[] {"git","init"};

and then execute the next command with its arguments.

I think we need to pass each argument as a separate array element because when executing notepad myfile.txt I would have to do..

String st[] = { "notepad", "myfile.txt"};
Process p = Runtime.getRuntime().exec(st,null,new File("D:/test dir/"));

So you could also do something like

String st[] = {"git","init"}

See the following gist

JavaTechnical
  • 8,846
  • 8
  • 61
  • 97
0

I don't know if you note this but you are missing the last letter '4' -> "cd C:/Users/Lennart/sciebo/Semster 2/Info/RepoCreator/Abgabe 4"

If it is just a typo, maybe you can try using double bar, by example:

 C:\\Users\\Lennart\\...\\
0

Don't you have to escape the slash characters?

ilmu011
  • 80
  • 2
  • 8