使用Runtime.getRuntime().exec()方法可以在java程式裡運作外部程式.
該方法有6個可通路版本:
1.exec(String command)
2.exec(String command, String envp[], File dir)
3.exec(String cmd, String envp[])
4.exec(String cmdarray[])
5.exec(String cmdarray[], String envp[])
6.exec(String cmdarray[], String envp[], File dir)
一般的應用程式可以直接使用第一版本,當有環境變量傳遞的時候使用後面的版本.
其中2和6版本可以傳遞一個目錄,辨別目前目錄,因為有些程式是使用相對目錄的,是以就要使用這個版本.
當要執行批處理的時候,不能直接傳遞批處理的檔案名,而要使用:
cmd.exe /C start 批處理檔案名
使用dos指令(比如dir)時也要使用掉調用.
如果想與調用的程式進行互動,那麼就要使用該方法的傳回對象Process了,通過Process的getInputStream(),getOutputStream(),getErrorStream()方法可以得到輸入輸出流,然後通過InputStream可以得到程式對控制台的輸出資訊,通過OutputStream可以給程式輸入指令,這樣就達到了程式的交換功能.
例子如下:
package com.broadcontact.netadmin.schedule;
import java.io.PrintWriter;
import java.io.PrintStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Date;
import java.io.StringReader;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.Reader;
import java.io.File;
import java.io.BufferedWriter;
import java.io.OutputStreamWriter;
/**
* <p>Title: netadmin</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2002</p>
* <p>Company: nm group</p>
* @author Maico(Panghf)
* @version 1.0
*/
public class ExecuteTask implements Runnable {
private boolean isRunning=true;
public ExecuteTask() {
}
public void run(){
}
public static void main(String[] args){
try {
Process proc=Runtime.getRuntime().exec("cmd.exe");
BufferedReader read=new BufferedReader(new InputStreamReader(proc.getInputStream()));
new Thread(new Echo(read)).start();
PrintWriter out=new PrintWriter(new OutputStreamWriter(proc.getOutputStream()));
BufferedReader in=new BufferedReader(new InputStreamReader(System.in));
String instr = in.readLine();
while(!"exit".equals(instr)){
instr = in.readLine();
out.println(instr);
file://out.println("telnet 192.168.0.1");
out.flush();
}
in.readLine();
read.close();
out.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
class Echo implements Runnable {
private BufferedReader read;
public Echo(BufferedReader read){
this.read = read;
}
public void run() {
try {
String l = read.readLine();
while (l != null) {
System.out.println(l);
l = read.readLine();
}
System.out.println("---執行完畢:");
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}