如何在Java中调用Python代码(2)

因为在Python程序中使用了第三方的NumPy模块,导致无法通过Jython执行,又由于个人水平的限制无法完全用Java重写,不得不出此下策。下面纯粹是个人思路,没有深入查资料。思路大概是:仅仅是通过Java执行一个本地程序(未必是.Py),然后通过一个本地文件做数据交互。

 核心代码如下:

import java.io.*; class PyCaller { private static final String DATA_SWAP = "temp.txt"; private static final String PY_URL = System.getProperty("user.dir") + "\\test.py"; public static void writeImagePath(String path) { PrintWriter pw = null; try { pw = new PrintWriter(new FileWriter(new File(DATA_SWAP))); } catch (IOException e) { e.printStackTrace(); } pw.print(path); pw.close(); } public static String readAnswer() { BufferedReader br; String answer = null; try { br = new BufferedReader(new FileReader(new File(DATA_SWAP))); answer = br.readLine(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return answer; } public static void execPy() { Process proc = null; try { System.out.println(System.getProperty("user.dir") + "\\test.py"); proc = Runtime.getRuntime().exec("python " + PY_URL); proc.waitFor(); } catch (IOException e) { e.printStackTrace(); } catch (InterruptedException e) { e.printStackTrace(); } } // 测试码 public static void main(String[] args) throws IOException, InterruptedException { writeImagePath("D:\\labs\\mytest\\test.jpg"); execPy(); System.out.println(readAnswer()); } }

实际上就是通过Java执行一个命令行指令。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/2d75970ac102673cbf4d794452f66f2f.html