Python 如何调用 Java

Section1:利用JPype实现Python调用Java

参考网址:

http://blog.csdn.net/niuyisheng/article/details/9002926

下面举例说明:

入门HelloWorld

1. from jpype import *

2. import os.path

3. startJVM("F:/java/java8/jre/bin/client/jvm.dll", "-ea")

4. java.lang.System.out.println("hello world")

调用第三方扩展包

1. from jpype import *

2. import os.path

3. jarpath = os.path.join(os.path.abspath('.'), 'F:/java/java_library/')

4. startJVM("F:/java/java8/jre/bin/client/jvm.dll","-ea", "-Djava.class.path=%s" % (jarpath + 'jsoup-1.8.1.jar'))

5. JDClass = JClass("org.jsoup.Jsoup")

6. jd = JDClass.connect("http://www.baidu.com").get()

7. jprint = java.lang.System.out.println

8. jprint(jd.outerHtml())

9. shutdownJVM()

 

Section2:Java调用Python利用

Runtime.getRuntime().exec("python test.py")

 

public class JavaCallPython {

public static void main(String[] args){

System.setProperty("PATH", "C:/Python27");

try{

System.out.println("start");

Process pr = Runtime.getRuntime().exec("python PythonCallJava.py");

BufferedReader in = new BufferedReader(new

InputStreamReader(pr.getInputStream()));

String line;

while ((line = in.readLine()) != null) {

System.out.println(line);

}

in.close();

pr.waitFor();

System.out.println("end");

} catch (Exception e){

e.printStackTrace();

}

}

}

注意这里需要设置python安装目录

怎么才能在Eclipse里也能正常运行了,可以通过

方法一:

System.setProperty("PATH", "python_home");

方法二:

在run configurations->environment新建一个PATH,值设为安装的python的路径,再运行就OK了。

你可能感兴趣的:(Python 如何调用 Java)