开发者

Problem with the output of a cmd command in java

I am trying to read in the results of a cmd command (dir for example). After creating the process, I use a BufferedReader in conjunction with an InputStreamReader. For some reason, the BufferedReader keeps coming up empty, even though I know that there must be some output to be read.

Here is the code I'm using:

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

        Process p = rt.exe开发者_运维百科c(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();
    }


You've got:

String[] str = new String[] {"cmd.exe", "/c", 
            "cd", "c:\\",
            "dir", "/b", "/s"               
    };

which doesn't seem right to me. You can't put multiple commands to cmd.exe on one command line. Thats a batch file.

Try getting rid of everything either the cd or the dir.

edit: indeed:

C:\>cmd.exe /c cd c:\ dir
The system cannot find the path specified.


There could be an error. In this case you should also trap getErrorStream()


The command you are running is cmd.exe /c cd c:\ dir /b /s. I don't think that's doing what you expect.


I mean that you have concatenated two commands into one line and the Windows shell probably doesn't like that. Try something like

String[] str = new String[] {"cmd.exe", "/c", 
            "cd", "c:\\", "&&",
            "dir", "/b", "/s"               
    };

The && will tell the shell to execute cd c:\ and then to execute dir /b /s if the first command was successful.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜