[英]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). 我试图读取cmd命令的结果(例如dir)。 After creating the process, I use a
BufferedReader
in conjunction with an InputStreamReader
. 创建进程后,我将
BufferedReader
与InputStreamReader
结合使用。 For some reason, the BufferedReader
keeps coming up empty, even though I know that there must be some output to be read. 出于某种原因,即使我知道必须要读取一些输出,
BufferedReader
也会一直空着。
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.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();
}
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.
您不能在一个命令行上将多个命令放到cmd.exe中。 Thats a batch file.
那是一个批处理文件。
Try getting rid of everything either the cd or the dir. 尝试摆脱cd或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()
在这种情况下,您还应该捕获getErrorStream()
The command you are running is cmd.exe /c cd c:\\ dir /b /s
. 您运行的命令是
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. 我的意思是你将两个命令连接成一行,而Windows shell可能不喜欢这样。 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. &&
将告诉shell执行cd c:\\
然后在第一个命令成功时执行dir /b /s
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.