1.java調用.exe文件
1、首先準備一個.exe程序,比如我桌面有一個代碼反編譯程序:jd-gui.exe。此處也可用其他的.exe程序,如電腦上安裝的瀏覽器程序等。
2、編寫代碼:
public static void main(String[] args) {
//.exe程序所在的完整路徑
String arguments = "D:\\tools\\jd-gui-windows-1.6.3\\jd-gui.exe";
try {
//執行這個.exe程序
Process process = Runtime.getRuntime().exec("cmd /c start " + arguments);
// 獲取程序執行後返回的結果
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
//java代碼中的process.waitFor()返回值爲0表示我們執行.exe文件成功,
//返回值爲1表示執行.exe文件失敗,這和我們通常意義上見到的0與1定義正好相反
int re = process.waitFor();
System.out.println(re);
} catch (Exception e) {
e.printStackTrace();
}
}
3、結果:上面代碼執行完畢後,jd-gui這個程序被成功打開,電腦屏幕上出現jd-gui的窗口。
2. java調用python
1、首先需要在電腦上安裝python環境:
1.1、下載鏈接:https://www.python.org/downloads/,根據電腦系統位數下載對應版本;
1.2、安裝:
注意:第一張圖中畫紅框的選項需要勾上,該選項是將python加入到系統環境變量path中。
1.3、測試python是否安裝成功:
2、準備python文件,命名爲test.py:
新建一個txt文件,輸入內容:
def hello():
print('Hello,Python')
if __name__ == '__main__':
hello()
保存後修改文件後綴名爲.py即可。
3、編寫java調用python的代碼:
// 依次爲:python.exe的安裝路徑,test.py腳本的存儲路徑
String[] arguments = new String[] {"D:\\Program Files\\Python\\python.exe", "E:\\work\\svn\\toolCluster\\ToolCluster\\01-01-ldrk-V1.2\\01-step1\\test.py"};
try {
// 運行test.py
Process process = Runtime.getRuntime().exec(arguments);
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream(),"GBK"));
String line = null;
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
//java代碼中的process.waitFor()返回值爲0表示我們調用python腳本成功,
//返回值爲1表示調用python腳本失敗,這和我們通常意義上見到的0與1定義正好相反
int re = process.waitFor();
System.out.println(re);
} catch (Exception e) {
e.printStackTrace();
}
4、結果:上述代碼執行成功後,控制檯會打印“Hello,Python”