【发布时间】:2010-02-05 01:27:05
【问题描述】:
我正在尝试读取 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();
}
【问题讨论】:
-
process.getErrorStream() 是否也返回空?
-
是的 - ErrorStream 和 InputStream 都有 0 个字节可用
-
我刚刚又跑了一遍,错误流不为空。当我阅读错误流时,它打印“系统找不到指定的路径”,这并不完全有意义,但至少它是一些东西。
-
尝试强制文件的物理地址,
C:\\test.txt看看会发生什么 -
这可能意味着 cmd.exe 不在 PATH 中(或 %PATH%,或者在 Windows 上调用的任何内容)。您可以尝试使用可执行文件的完整路径,至少一开始可以吗?