繁体   English   中英

在java中输出cmd命令的问题

[英]Problem with the output of a cmd command in java

我试图读取cmd命令的结果(例如dir)。 创建进程后,我将BufferedReaderInputStreamReader结合使用。 出于某种原因,即使我知道必须要读取一些输出, 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();
    }

你有:

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

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

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

编辑:确实:

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

可能有错误。 在这种情况下,您还应该捕获getErrorStream()

您运行的命令是cmd.exe /c cd c:\\ dir /b /s 我认为这不符合你的期望。


我的意思是你将两个命令连接成一行,而Windows shell可能不喜欢这样。 尝试类似的东西

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

&&将告诉shell执行cd c:\\然后在第一个命令成功时执行dir /b /s

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM