chama
chama

Reputation: 6163

CMD.exe command in java not terminating

I'm trying to use cmd.exe to search for a file in a specific directory and then display the path in a java program and write it to a file. The problem is that the process never terminates.

Here is my code:

String[] str = new String[] { "cmd.exe ", "cd c:\\",
                        " dir /b /s documents", "2>&1" };

            Runtime rt = Runtime.getRuntime();
            try{

                Process p = rt.exec(str);
                InputStream is =p.getInputStream();
                InputStreamReader in = new InputStreamReader(is);


                StringBuffer sb = new StringBuffer();
                BufferedReader buff = new BufferedReader(in);
                String line = buff.readLine();
                while( line != null )
                {
                    sb.append(line + "\n");
                    line = buff.readLine();
                }
                System.out.println( sb );
                File f = new File("test.txt");
                FileOutputStream fos = new FileOutputStream(f);
                fos.write(sb.toString().getBytes());
                fos.close();

            }catch( Exception ex )
            {
                ex.printStackTrace();
            }

Upvotes: 3

Views: 3271

Answers (4)

piapplications
piapplications

Reputation: 11

You must use the start command in addition to the cmd.exe process with the /C or /K switch BEFORE the start command. Example: to convert the Windows's command interpreter in a bash console (from the mingw prroject) you must invoke the exec method of the Runtime class with the command "C:\Windows\System32\cmd.exe /C start C:\mingw\msys\1.0\bin\bash.exe" (I use an external command rather than an internal because it's more signifiant but you can use internal command like DIR and so on).

Upvotes: 0

ghostdog74
ghostdog74

Reputation: 343171

why are not using Java to do directory traversal instead of calling external shell command? It makes your code not portable!

Upvotes: 0

karoberts
karoberts

Reputation: 9938

Runtime.exec doesn't work that way. You can't pass multiple commands like that to cmd.exe.

Runtime.exec allows you to execute a single process with a list of arguments. It does not provide any "shell" operations (like 2>&1 for instance). You must do that sort of IO redirection yourself using the Input/Output streams.

It's similar to calling another program's main function.

You could try `Runtime.exec( new String[] { "cmd.exe", "/c", "dir", "C:\\" } );

But realistically, if you want file listings, you're much better off using the facilities in the java.io.File class, which won't depend on operating system specific features.

Upvotes: 1

tangens
tangens

Reputation: 39753

Please try

cmd /c

instead of simply

cmd

Reference

Upvotes: 1

Related Questions