运行一个外部程序并捕获输出在Java中运行一个外部程序是使用java.lang.Runtime类的方法exec().该方法返回一个Process类。 如果你想捕获运行程序的输出,就要使用Process类。Process类有三个方法:. Process.getOutputStream(), Process.getInputStream(), Process.getErrorStream().分别对应于stdin, stdout, stderr。因此 如果想要捕捉该程序的输出,就要使用Process.getInputStream()。下面的例子就是运行dir程序,然后 把它的输出打印到屏幕上。所产生的效果和直接运行dir 程序是一样的。
import java.io.*;class Main {
public static void main(String[] args) {
try {
String cmd = "dir";
Process child = Runtime.getRuntime().exec(cmd);
// 获得dir的输出
InputStream child_in = child.getInputStream();
int c;
while ((c = child_in.read()) != -1)
{
System.out.print((char)c);
}
child_in.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
import java.io.*;class Main {
public static void main(String[] args) {
try {
String cmd = "dir";
Process child = Runtime.getRuntime().exec(cmd);
// 获得dir的输出
InputStream child_in = child.getInputStream();
int c;
while ((c = child_in.read()) != -1)
{
System.out.print((char)c);
}
child_in.close();
} catch (IOException e) {
System.err.println(e);
}
}
}
}
public static void main(String[] args) {
try {
String cmd = "cmd dir f:>>f:/aaa.txt";
String cmd1 = "cmd net view";
Process child = Runtime.getRuntime().exec(cmd1); // 获得dir的输出
InputStream child_in = child.getInputStream() ;DataInputStream in=new DataInputStream(child_in); int c;
String szstr1="";
while ((szstr1 = in.readLine())!=null){
System.out.print(szstr1);
}
child_in.close();
in.close() ;
} catch (IOException e) {
System.err.println(e);
}
}}
我用了以上程序,仅仅出来了以下句子:
Microsoft Windows 2000 [Version 5.00.2195](C) °??¨?ù?? 1985-1998 Microsoft Corp.根本得不到预计的目的.
public static void main(String[] args) {
try {
String cmd = "cmd dir f:";
String cmd1 = "cmd net view";
Process child = Runtime.getRuntime().exec(cmd);
InputStream child_in = child.getInputStream() ;
int c;
while ((c = child_in.read())!=-1){
System.out.print((char)c);
}
child_in.close();
child.destroy() ;
} catch (IOException e) {
System.err.println(e);
}
}
}
我用了以上程序,仅仅出来了以下句子:
Microsoft Windows 2000 [Version 5.00.2195](C) °??¨?ù?? 1985-1998 Microsoft Corp.F:\my_bag\JBuilder6.0\NetSender>然后程序就停止了,但是没有退出.根本得不到预计的目的.
这是我的帖子:http://expert.csdn.net/Expert/topic/1266/1266041.xml?temp=.4998896请帮忙!谢谢
Process process = Runtime.getRuntime().exec(command);
BufferedReader bufferedReader = new BufferedReader( new InputStreamReader(process.getInputStream()) );
process.getInputStream().read(data);
FileWriter fout=new FileWriter (Filename);
while ( (ls_1=bufferedReader.readLine()) != null)
{ fout.write(ls_1);
fout.write('\n');
System.out.println(ls_1);
}其中Filename 为你想输出的文本文件!
此代码在我这正常