Java 调用执行其他语言的程序

一般的场景可以通过使用 Runtime.getRuntime().exec() 来完成,该命令返回一个 Process 对象实例。

...
String[] cmdArgs = {"Rscript", medreportPath, "-i", destFilePath1, "-o", webRptPath + "/" + runID}; // String command = "Rscript " + medreportPath + " -i " + destFilePath1 + " -o " + webRptPath + "/" + runID; try { Process process = Runtime.getRuntime().exec(cmdArgs); // 调动外部程序 BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream(), StandardCharsets.UTF_8)); // 获取标准输出 String line; while ((line = br.readLine()) != null) { System.out.println(line + " "); } BufferedReader brError = new BufferedReader(new InputStreamReader(process.getErrorStream(), StandardCharsets.UTF_8)); // 获取标准错误输出 String lineError; while((lineError = brError.readLine()) != null) { System.out.println(lineError + " "); } process.waitFor(); } catch (Exception e) { e.printStackTrace(); }
...

以 Java 调用 Python 为例

1. 使用 Runtime 类

该方式简单,但是增加了 Java 对python 的依赖,需要事先安装python,及python程序依赖的第三方库

Runtime 使用了单例模式,只能使用 Runtime 的 static 方法获取实例

可以调用 exec() 来执行外部程序,返回 Process 对象实例

public class Runtime extends Object // Runtime 直接继承 Object
public static Runtime getRunTime()  // 获取 Runtime 实例的 static 方法
public Process exec(...) throws IOException  // 执行外部程序,exec()有多个重载方法 

例子

Java 程序代码

package java_python;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;

/*
 *  直接使用 Runtime 调用外部程序
 *  在Java中通过Runtime调用Python程序与直接执行Python程序的效果是一样的,可以在Python中读取传递的参数,也可以在Java中读取到Python的执行结果。
 *  需要注意的是,不能在Python中通过return语句返回结果,只能将返回值写入到标准输出流中,然后在Java中通过标准输入流读取Python的输出值。
 */
public class RunPythonByRuntime {
    public static void main(String[] args) {
        String exe = "python";  // 使用python3   依赖biopython
        String command = "C:\Users\mail.simcere.com\eclipse-workspace\python_test\test\test01.py";  // python 脚本路径
        String term = "meningitis";  // 参数
        String[] cmdArr = new String[] {exe, command, term};
        Process process;
        try {
            process = Runtime.getRuntime().exec(cmdArr);  // 执行python程序
            InputStream inputStream = process.getInputStream();  // 获取python程序的标准输出
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));  // 转换为BufferedReader对象实例
            String line = null;
            while((line = bufferedReader.readLine()) != null) {  // 逐行读入python程序的输出结果
                System.out.println(line);
            }
            process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Python 程序代码

#coding=utf-8

import sys
from Bio import Entrez
from Bio import Medline

term = sys.argv[1]  # 需要外界传入 meningitis
retmax = 5  # 控制返回的文献数目
Entrez.email = "771966294@qq.com"
handle = Entrez.esearch(db="pubmed", term=term, retmax=retmax)
record = Entrez.read(handle)
handle = Entrez.efetch(db="pubmed", id=record["IdList"], rettype="medline", retmode="text")
records = Medline.parse(handle)
records = list(records)
handle.close()
rst = ""
for record in records:  # record 是一个字典
    rst += ">
PMID:" + record.get("PMID", "?") 
         + "
Title:" + record.get("TI", "?") 
         + "
Authors:" + ";".join(record.get("AU", "?")) 
         + "
Abstract:" + record.get("AB", "?") 
         + "
Keywords:" + ";".join(record.get("OT", "?")) 
         + "
Mesh Terms:" + ";".join(record.get("MH", "?")) 
         + "
Journal:" + record.get("TA", "?") 
         + "
Date of Publication:" + record.get("DP", "?") 
         + "
doi:" + record.get("SO", "?") 
         + "
"
print(rst)

2. 使用 Jython 需要事先安装 Jython

通过 Jython 可以实现 Java 和 Python 的互相调用,使粒度更加精细,但并没用解决耦合度的问题。

https://www.cnblogs.com/nuccch/p/8435693.html

原文地址:https://www.cnblogs.com/0820LL/p/10755240.html