3

I need to execute the following Change directories commands into the cmd prompt, but using java to execute them. the dir command works fine , but not the cd ones. I have to execute them in a single cmd windows

cd inputDir
dir
cd outputDir

inputDir and outputDir are directories from the windows.

Java Snippet:

ArrayList<String> dosCommands = new ArrayList<String>();
Process p;
for (int i=0;i< dosCommands.size();i++){
    p=Runtime.getRuntime().exec("cmd.exe /c "+dosCommands.get(i)); 
    p.waitFor();
    BufferedReader reader=new BufferedReader(new InputStreamReader(p.getInputStream()));
    String line=reader.readLine();
    while(line!=null) 
    { 
        System.out.println(line); 
        line=reader.readLine(); 
    } 
}

UPDATE

Changing the argument to cmd.exe /k instead of /c

p=Runtime.getRuntime().exec("cmd.exe /k "+dosCommands.get(i)); 

I had to remove the

p.waitFor(); 

method, because I was getting stucked in it. Doing so, know I do get stucked in the

line.reader.readLine(); 
5
  • 1
    Could you describe in more details what "does not work" mean? Could you provide some output of your code and what you expect to happen? Commented Jun 29, 2015 at 19:24
  • The command works but you dont get any answer. After the command is executed the cmd.exe is closed. Commented Jun 29, 2015 at 19:25
  • @IvanMushketyk Yes, When I execute the cd inputDir, it shold change directory to the input dir directory. I check that by executing a dir command after the cd inputDir. The dir command print another directory unfortunately. Commented Jun 29, 2015 at 19:34
  • Do by any chance you change directory from one partition to another one? If so you need to use "cd <partition-letter>" first and then cd <target-path> Commented Jun 29, 2015 at 19:36
  • Here are some of the cd commands I tried to execute: cd C:\Users\eleite\Workspace\RunCmd\Petrel_Logs cd C:\Users\eleite\Workspace\RunCmd\Petrel2014LicenseModuleLogging Commented Jun 29, 2015 at 19:43

3 Answers 3

2

use

cmd.exe /K

Not

cmd.exe /c

You can find more about cmd params here

With /c, cmd finishes and exit. With /k, it does not exit.

__UPDATE__

What I mean is as follows:

cd inputDir
dir
cd outputDir
exit

Pay attention to the last line please.

__UPDATE 2__

Please use something similar in your code to find out what is the current working directory, according to running process:

public class JavaApplication1 {
  public static void main(String[] args) {
       System.out.println("Working Directory = " +
              System.getProperty("user.dir"));
  }
}

After that, let's make sure that the folders you are trying to cd to exists in that folder.

Sign up to request clarification or add additional context in comments.

6 Comments

That seems to be a path to the solution, but now I cant read the output of a line and get stucked at the p.waitFor();
Did you try adding an exit statement at the end of your batch file ?
I need to execute all the commands in a single cmd window, not one by one.
@Eduardox23 Here is code example: ideone.com/KjVOjc (not working on ideone but should work on your Windows).
@Eduardox23 Did you at least make any progress ? If so, please update your question so we know where you are at. If not, would you post what do you after you run the script ? (Like a screen shot, error etc).
|
1

Try this experiment: Open a command window (using your mouse and/or keyboard, not with code). Now change to a different directory, with a command like cd \ or cd C:\Windows.

Then open a second command window. What is its current directory? Did it remember what you did in the first command window?

It didn't, because each time you run cmd.exe you are starting a new process, with its own current directory state.

In your code, you are executing a new cmd.exe process in each iteration of your for-loop. Each time you start a new cmd.exe, it has no awareness of what the current directory may be in other cmd.exe instances.

You can set the current directory in which a process executes:

String inputDir = "C:\\Users\\eleite\\Workspace\\RunCmd\\Petrel_Logs";
p = Runtime.getRuntime().exec("cmd.exe /c " + dosCommands.get(i),
    null, inputDir); 

5 Comments

Yes you are right. Is there a way to execute all the commands in a single cmd window ? so I do not have to pass the dir with the command ?
Write the commands to a .bat file, and pass it to cmd.exe /c.
@Eduardox23 You can pass each command to Process handling console via its input stream. If you don't want to do this in main thread create separate one.
@vgr I don't want o use a .bat file, I want all the commands to be inside the java code.
@Pshemo I'm sory i did not get it, can you provide an example ?
0

If you want to

  • create process simulating console
  • and make this console execute few commands
  • and after these commands are executed continue code from main thread

then try this code

ProcessBuilder pb = new ProcessBuilder("cmd.exe", "/k");
pb.redirectOutput(Redirect.INHERIT);//redirect process output to System.out
pb.redirectError(Redirect.INHERIT);//redirect process output to System.err
Process p = pb.start();

try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()), true)){
    pw.println("dir");//execute command 1, for instance "dir"
    pw.println("ver");//execute command 2, for instance "ver"
    //... rest of commands
    pw.println("exit");//when last command finished, exit console
}
p.waitFor();//this will make main thread wait till process (console) will finish (will be closed)
//here we place rest of code which should be executed after console after console process will finish
System.out.println("---------------- after process ended ----------------");

So if you want list of commands you want to execute simply place them here:

try(PrintWriter pw = new PrintWriter(new OutputStreamWriter(p.getOutputStream()), true)){

    //here and execute them like 
    for (String command : dosCommands){
        pw.println(command);
    }        

    pw.println("exit");//when last command finished, exit console
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.