java中的CMD.exe命令没有终止

时间:2010-02-04 15:11:17

标签: java cmd terminate

我正在尝试使用cmd.exe搜索特定目录中的文件,然后在java程序中显示该路径并将其写入文件。问题是该过程永远不会终止。

这是我的代码:

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

4 个答案:

答案 0 :(得分:1)

请尝试

cmd /c

而不是简单

cmd

Reference

答案 1 :(得分:1)

Runtime.exec不起作用。您无法将多个命令传递给cmd.exe。

Runtime.exec允许您使用参数列表执行单个进程。它不提供任何“shell”操作(例如2>&1)。您必须使用输入/输出流自己进行那种IO重定向。

这与调用另一个程序的main函数类似。

您可以尝试`Runtime.exec(new String [] {“cmd.exe”,“/ c”,“dir”,“C:\\”});

但实际上,如果你想要文件列表,你最好使用java.io.File类中的设施,这不依赖于操作系统特定的功能。

答案 2 :(得分:0)

为什么不使用Java to do directory traversal而不是调用外部shell命令?它使你的代码不可移植!

答案 3 :(得分:0)

在启动命令之前,除了使用/ C或/ K开关的cmd.exe进程外,还必须使用start命令。示例:要在bash控制台(来自mingw项目)中转换Windows的命令解释器,必须使用命令“C:\ Windows \ System32 \ cmd.exe / C start C:\ mingw \”调用Runtime类的exec方法msys \ 1.0 \ bin \ bash.exe“(我使用外部命令而不是内部命令,因为它更有意义但你可以使用内部命令,如DIR等)。

相关问题