在java中输出cmd命令的问题

cha*_*ama 7 java cmd

我试图读取cmd命令的结果(例如dir).创建过程后,我使用了BufferedReader一个InputStreamReader.出于某种原因,BufferedReader尽管我知道必须要读取一些输出,但它仍然是空的.

这是我正在使用的代码:

String[] str = new String[] {"cmd.exe", "/c", 
            "cd", "c:\\",
            "dir", "/b", "/s"               
    };
    Runtime rt = Runtime.getRuntime();
    try{

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

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

            fos.close();
        }
    }catch( Exception ex )
    {
        ex.printStackTrace();
    }
Run Code Online (Sandbox Code Playgroud)

Tre*_*son 5

你有:

String[] str = new String[] {"cmd.exe", "/c", 
            "cd", "c:\\",
            "dir", "/b", "/s"               
    };
Run Code Online (Sandbox Code Playgroud)

这似乎对我不对.您不能在一个命令行上将多个命令放到cmd.exe中.那是一个批处理文件.

尝试摆脱cd或dir的所有内容.

编辑:确实:

C:\>cmd.exe /c cd c:\ dir
The system cannot find the path specified.
Run Code Online (Sandbox Code Playgroud)

  • @chama:如果只使用`dir/b/s C:\`?只是为了它的乐趣:尝试从另一个驱动器运行您的代码,例如`D:`.你的`cd`命令在那里什么都不做.通常,使用任何适用的东西,不要试图使事情过于复杂.这是一个示例,您只需要一个可以执行所需操作的命令.那两个序列不会. (2认同)