我正在尝试读取 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();
}
最佳答案
你有:
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.
关于java - java中cmd命令的输出问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2201513/