如何用java执行命令行

用执行命令行:
如 1. 转入某个directory, 如 cd d:
2. 执行一个命令行 如:mallet import-dir.

Java运行命令行并获取返回值,下面以简单的Java执行ping命令(ping 127.0.0.1 -t
)为例,代码如下:

Process p = Runtime.getRuntime().exec("ping 127.0.0.1 -t");
Process p = Runtime.getRuntime().exec("javac");
InputStream is = p.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
String line;
while((line = reader.readLine())!= null){
   System.out.println(line);
  }
p.waitFor();
is.close();
reader.close();
p.destroy();
}
温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-01-30
运行cmd.exe 这个程序捕捉process.get InputStream 读取输出,捕捉.getOutputStream 发送命令。追问

你好,谢谢
能再详细一下吗?
Runtime rt= Runtime.getRuntime();
String []cmd= {"c:\\","mallet import-dir --number 10"};//mallet 是一个运行程序
Process pr = rt.exec(cmd);
我这样运行,有错误,网上我也找不到多条语句怎么运行?
我不需要读取输出,只要能像在command line里面运行一样即可。

追答

你把 response 里面的 run 方法改成你要的, request 里面的 run 方法是发送命令。样例中我向 request 中发送了 dir 命令,然后在 response 中得到了输出。

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
public class Main {
public static void main(String[] args) throws IOException {
Process shell = Runtime.getRuntime().exec("cmd.exe");
final InputStream input = shell.getInputStream();
final OutputStream output = shell.getOutputStream();
Thread request = new Thread() {
public void run() {
try {
output.write("dir".getBytes());
} catch (Exception e) {
e.printStackTrace();
}
}
};
request.start();
Thread response = new Thread() {
public void run() {
int c = -1;
byte[] buf = new byte[512];
try {
while ((c = input.read(buf)) != -1) {
System.out.print(new String(buf, 0, c));
}
} catch (Exception e) {
e.printStackTrace();
}
}
};
response.start();
}
}

本回答被网友采纳
第2个回答  2013-02-01
C盘转D盘 应该是直接
C:\>d:
D:\>
不用CD
执行mallet import-dir.的话 首先要确认mallet.exe或者mallet.cmd在当前目录,或者存在与环境变量指定的目录,否则要加上路径 比如D:\> C:\JDK1.5\BIN\JAVAC 11.JAVA
相似回答