可能重复:
从一个进程获取输出
从Java执行DOS命令
我试图从一个JAVA控制台程序内运行cmd命令,例如:
ver
然后将命令的输出返回到JAVA中的string,如输出:
string result = "Windows NT 5.1"
你可以使用下面的代码
import java.io.*; public class doscmd { public static void main(String args[]) { try { Process p=Runtime.getRuntime().exec("cmd /c dir"); p.waitFor(); BufferedReader reader=new BufferedReader( new InputStreamReader(p.getInputStream()) ); String line; while((line = reader.readLine()) != null) { System.out.println(line); } } catch(IOException e1) {e1.printStackTrace();} catch(InterruptedException e2) {e2.printStackTrace();} System.out.println("Done"); } }
您可以使用java中的Runtime exec从Java代码执行dos命令。
Process p = Runtime.getRuntime().exec("cmd /C ver"); BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()),8*1024); BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream())); // read the output from the command String s = null; System.out.println("Here is the standard output of the command:\n"); while ((s = stdInput.readLine()) != null) System.out.println(s.replace("[","").replace("]",""));
输出= Microsoft Windows Version 6.1.7600
你可以做一些事情:
String line; Process p = Runtime.getRuntime().exec ("ver"); BufferedReader input =new BufferedReader(new InputStreamReader(p.getInputStream())); BufferedReader error =new BufferedReader(new InputStreamReader(p.getErrorStream())); System.out.println("OUTPUT"); while ((line = input.readLine()) != null) System.out.println(line); input.close(); System.out.println("ERROR"); while ((line = error.readLine()) != null) System.out.println(line); error.close();
在@RanRag的评论,主要问题是Windows与Unix / Mac。
看一看java.lang.Runtime
或者更好一些, java.lang.Process
这可能会帮助你开始。