Search code examples
javacmdterminate

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();
            }

Solution

  • Please try

    cmd /c
    

    instead of simply

    cmd
    

    Reference