开发者

CMD.exe command in java not terminating

开发者 https://www.devze.com 2022-12-18 22:36 出处:网络
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.

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();
开发者_如何学C
            }catch( Exception ex )
            {
                ex.printStackTrace();
            }


Please try

cmd /c

instead of simply

cmd

Reference


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.


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


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).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号