我正在编写一些程序来使用附加命令调用 cmd.exe 并使用 java 收集从相同生成的输出。下面是一个示例程序——
public class LoadShell {
public static void main(String[] args) throws Exception {
//Line1
String [] command ={"cmd.exe","/c","dir"};
ProcessBuilder probuilder = new ProcessBuilder( command );
Process process = probuilder.start();
InputStream inputstream1 = process.getInputStream();
InputStreamReader inputstreamreader1 = new InputStreamReader(inputstream1);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader1);
String line="";
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
}
}
这些程序按预期运行良好。现在我有一个更简单的要求。我想在没有任何参数的情况下调用 cmd.exe 并将输出收集为字符串。这是因为我想将流程对象引用和字符串发送到另一个方法以用于某些项目特定目的。所以我在 Line1 中修改了我的代码,如下所示——
public class LoadShell {
public static void main(String[] args) throws Exception {
//Line1
String [] command ={"cmd.exe"};
ProcessBuilder probuilder = new ProcessBuilder( command );
Process process = probuilder.start();
InputStream inputstream1 = process.getInputStream();
InputStreamReader inputstreamreader1 = new InputStreamReader(inputstream1);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader1);
int intch;
String line="";
while ((line = bufferedreader.readLine()) != null) {
System.out.println(line);
}
}
}
但在这种情况下,该readLine
方法在打印后无限期挂起——
Microsoft Windows [版本 6.1.7601] 版权所有 (c) 2009 Microsoft Corporation。版权所有。
所以我也尝试过使用 read ofBufferedReader
而不是readline
如下 -
while ((intch = bufferedreader.read()) != -1) {
int ch = (char) intch;
System.out.println(ch);
}
但是在读取对应的字节后,即使读取也挂起-
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
有什么方法可以得到下面的完整输出而不会导致我的程序挂起——
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\devshankhasharm>
任何想法,将不胜感激。