我正在做一些需要我开始子处理(命令提示符)并在其上执行一些命令的事情。我需要从子进程获取输出并将其存储在文件或字符串中。 这是我到目前为止所做的,但它不起作用:
public static void main(String args[])
{
try
{
Runtime RT = Runtime.getRuntime();
String command = "cmd /c start javap java.lang.String";
File file = new File("write.txt");
Writer output = new BufferedWriter(new FileWriter(file));
BufferedReader br = new(BufferedReader(newInputStreamReader(RT.exec(command).getInputStream()));
String temp = br.readLine();
while(!temp.equals(null))
{
output.write(temp);
temp = br.readLine();
}
output.close();
RT.exec("exit");
}
catch(Exception e)
{
System.out.println(e);
}
}
最佳答案
开始更改:
new(BufferedReader(newInputStreamReader(
致:
new BufferedReader(new InputStreamReader(
编译看看是否还有问题
编辑
此外,有一个很好的理由说明为什么您不应该捕获异常,您还可以捕获像 NullPointerException
这样的编程错误。
while( !temp.equals(null)) { //Throws NullPointerExceptin when temp is null
更改为:
while( temp != null ) { //!temp.equals(null)) {
最后,您不必“退出”,因为您实际上并不在 cmd 内。
罢工><罢工>罢工>
更正版本
此版本按您的预期运行:
import java.io.*;
class Rt {
public static void main(String args[]) throws Exception {
Runtime RT = Runtime.getRuntime();
String command = "javap java.lang.String" ;
File file = new File("write.txt");
Writer output = new BufferedWriter(new FileWriter(file));
BufferedReader br = new BufferedReader(new InputStreamReader(RT.exec(command).getInputStream()));
String temp = br.readLine();
while( temp != null ) { //!temp.equals(null)) {
output.write(temp);
temp = br.readLine();
}
output.close();
//RT.exec("exit");
}
}
编辑 最后评论:
自 Java 1.5 起,调用命令的首选方法是使用 ProcessBuilder如果您使用字符串数组而不是单个字符串(或 varargs ),那就更好了。
当您构建输出时,您可以摆脱文件对象并将文件名直接传递给文件编写器。
在阅读该行时,您可以在条件中进行分配和评估。
Java 的编码约定建议使用左大括号。
这将是我的代码版本:
class Rt {
public static void main(String args[]) throws Exception {
Writer output = new BufferedWriter(new FileWriter ( "write.txt"));
InputStream in = new ProcessBuilder("javap", "java.lang.String").start().getInputStream();
BufferedReader br = new BufferedReader( new InputStreamReader(in));
String line = null;
while( ( line = br.readLine() ) != null ) {
output.write( line );
}
output.close();
}
}
可能还需要一些工作,但我希望它对您有所帮助。
关于java - 在 Java 中获取并存储子进程的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6575299/