今天折腾了下java中调用python的方法,上午在高手的指点下了个jar包,地址如下:http://sourceforge.net/projects/jpype/ 在cmd下用java jar jython_installer-2.5.2 会生成一个目录,里面会有一个jar文件和其他的目录,跟python有点相似,在eclipse下面把这个jar文件添加进去,然后下代码调用python,具体如下:
package test;
import java.io.FileInputStream;
import java.io.InputStream;
import org.python.core.Py;
import org.python.util.PythonInterpreter;
import org.python.core.PySystemState;
public class Jpython_exec{
public static void main(String[] args) throws Exception{
PythonInterpreter interpreter=new PythonInterpreter();
// PySystemState sys = Py.getSystemState();
interpreter.exec("print 'hello'");
interpreter.exec("import sys");
interpreter.exec("print sys.path");
interpreter.exec("for x in xrange(10):print x \n");
// interpreter.execfile("D:\\Users\\zhoumeixu204\\Desktop\\test.py");
// InputStream filepy = new FileInputStream("D:\\Users\\zhoumeixu204\\Desktop\\test.py");
}
}
//显示成功,但是执行interpreter.execfile("D:\\Users\\zhoumeixu204\\Desktop\\test.py"); 时候报错,原因是我在test里面装了第三方库,Jpython识别不了,在网上//折腾一段时间没解决,后来用另外一种办法完美解决,如果有高手知道用这种办法,可以联系我,见代码如下:
package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Jpython_pyhon_file {
public static void main(String[] args){
try{
System.out.println("start");
Process pr = Runtime.getRuntime().exec("python D:\\Users\\zhoumeixu204\\Desktop\\test.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做数据清洗比较方便,包括图形识别,机器学习等能快速实现,再用java调,这样会方便很多