Python 如何調用 Java

<h3>Section1:利用JPype實現Python調用Java</h3> <p>參考網址:</p> <p><a href="http://blog.csdn.net/niuyisheng/article/details/9002926">http://blog.csdn.net/niuyisheng/article/details/9002926</a></p> <p>下面舉例說明:</p> <h5>入門HelloWorld</h5> <p>1. from jpype import *</p> <p>2. import os.path</p> <p>3. startJVM(&quot;F:/java/java8/jre/bin/client/jvm.dll&quot;, &quot;-ea&quot;)</p> <p>4. java.lang.System.out.println(&quot;hello world&quot;)</p> <h5>調用第三方擴展包</h5> <p>1. from jpype import *</p> <p>2. import os.path</p> <p>3. jarpath = os.path.join(os.path.abspath('.'), 'F:/java/java_library/')</p> <p>4. startJVM(&quot;F:/java/java8/jre/bin/client/jvm.dll&quot;,&quot;-ea&quot;, &quot;-Djava.class.path=%s&quot; % (jarpath + 'jsoup-1.8.1.jar'))</p> <p>5. JDClass = JClass(&quot;org.jsoup.Jsoup&quot;)</p> <p>6. jd = JDClass.connect(&quot;http://www.baidu.com&quot;).get()</p> <p>7. jprint = java.lang.System.out.println</p> <p>8. jprint(jd.outerHtml())</p> <p>9. shutdownJVM()</p> <p>&#160;</p> <h4>Section2:Java調用Python利用</h4> <h4>Runtime.getRuntime().exec(&quot;python test.py&quot;)</h4> <p>&#160;</p> <p>public class JavaCallPython {</p> <p>public static void main(String[] args){</p> <p>System.setProperty(&quot;PATH&quot;, &quot;C:/Python27&quot;);</p> <p>try{</p> <p>System.out.println(&quot;start&quot;);</p> <p>Process pr = Runtime.getRuntime().exec(&quot;python PythonCallJava.py&quot;);</p> <p>BufferedReader in = new BufferedReader(new</p> <p>InputStreamReader(pr.getInputStream()));</p> <p>String line;</p> <p>while ((line = in.readLine()) != null) {</p> <p>System.out.println(line);</p> <p>}</p> <p>in.close();</p> <p>pr.waitFor();</p> <p>System.out.println(&quot;end&quot;);</p> <p>} catch (Exception e){</p> <p>e.printStackTrace();</p> <p>}</p> <p>}</p> <p>}</p> <p>注意這裏須要設置python安裝目錄</p> <p>怎麼才能在Eclipse裏也能正常運行了,能夠經過</p> <p>方法一:</p> <p>System.setProperty(&quot;PATH&quot;, &quot;python_home&quot;);</p> <p>方法二:</p> <p>在run configurations-&gt;environment新建一個PATH,值設爲安裝的python的路徑,再運行就OK了。</p>java

相關文章
相關標籤/搜索