在Java中, 如果需要调用第三方程序,可以直接通过Runtime实现,这也是最直接最粗暴的做法。
package testJavaUsePython;
import java.io.*;
//自动导包:alt+enter
public class test {
public static void main(String[] args) throws IOException, InterruptedException {
String line ;
String exe = "python";
String command = "D:\\softWare\\Python\\pythonrun\\BYSJ\\transE-master\\testDataTrue.py";
String num1 = "1";
String num2 = "2";
String[] cmdArr = new String[] {exe, command};
Process process = Runtime.getRuntime().exec(cmdArr);
InputStream is = process.getInputStream();
DataInputStream dis = new DataInputStream(is);
while ((line = dis.readLine()) != null) {
// line = decodeUnicode(line);
System.out.println(line);
}
process.waitFor();
}
//String command = "D:\\softWare\\Python\\pythonrun\\BYSJ\\transE-master\\testDataTrue.py";
}
有两点需要注意:
一、python程序中不能含有中文,否则输出到Java的控制台shan上可能会是luan乱码
二、python代码使用的文件路径一定要决定路径,不然Java代码是无法执行python代码的;