在Java中调用Python的方法有多种,以下是几种常见的方式:
使用`Runtime`类执行Python脚本
try {String command = "python path/to/python/script.py";Process process = Runtime.getRuntime().exec(command);BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = input.readLine()) != null) {System.out.println(line);}input.close();process.waitFor();} catch (InterruptedException | IOException e) {System.out.println("调用python脚本并读取结果时出错:" + e.getMessage());}
使用`ProcessBuilder`类执行Python脚本
ProcessBuilder pb = new ProcessBuilder("python", "path/to/python/script.py");Process process = pb.start();BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream()));String line;while ((line = input.readLine()) != null) {System.out.println(line);}input.close();process.waitFor();
在Java类中直接执行Python语句
import org.python.util.PythonInterpreter;public class JavaRunPython {public static void main(String[] args) {PythonInterpreter interpreter = new PythonInterpreter();interpreter.exec("a=5+2+3+9+4+0");interpreter.exec("print(sorted(a))");}}

调用Python脚本中的函数
import org.python.core.PyObject;import org.python.core.PyFunction;import org.python.util.PythonInterpreter;public class FirstJavaScript {public static void main(String args[]) {PythonInterpreter interpreter = new PythonInterpreter();interpreter.exec("def adder(a, b): return a + b");PyFunction add = interpreter.get("adder");PyObject result = add.__call__(new PyInteger(1), new PyInteger(2));System.out.println(result);}}
使用第三方库如Jython或PyJNIus
Jython:需要下载Jython的jar包,并在项目中引用。
PyJNIus:允许Python代码访问Java类,适用于Android开发等场景。
