views:

376

answers:

3

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();
            }
+1  A: 

Please try

cmd /c

instead of simply

cmd

Reference

tangens
I should put the cmd /c instead of cmd.exe as a command in str? If so, I tried that and got an IOException - The system cannot find the file specified.
chama
You have to put `/c` in a separate parameter. Runtime.exec( "cmd.exe", "/c", ... )
tangens
cmd.exe with the parameter /c so your code reads: `String[] str = new String[] { "cmd.exe", "/c", "\"cd c:\\
TommyA
Thank you tangens - I added /c as one of the parameters like TommyA said. The program terminated, but for some reason, now the StringBuffer is not finding the results.
chama
+1  A: 

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.

karoberts
A: 

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

ghostdog74