Java调用python脚本
最近也是刚开始学python,所以这里写了一个简单的小方法用Java来调用python脚本。后期再进行更新。
1、Java启动程序的方法
在Java中提供了两种方法来启动其他程序:
1. 使用Runtime的exec()方法
2. 使用ProcessBuilder的start()方法 。
本文中使用exec()方法来调用python脚本。
2、首先准备一个python程序
小编这里准备了一个最简单的python程序——单词反转。
直接上代码吧。
def reverse(str_list,start,end):
while start<end:
str_list[start], str_list[end] = str_list[end],str_list[start]
start +=1
end -=1
setence = ' Hello, how are you? Fine. '
str_list = list(setence)
i=0
while i<len(str_list):
if str_list[i] !=' ':
start = i
end = start + 1
while (end < len(str_list)) and str_list[end] !=' ':
end +=1
reverse(str_list, start, end -1)#先把每个单词进行反转
i = end
else:
i += 1
str_list.reverse()#然后再把整个字符串进行反转
print(''.join(str_list))
3、通过Runtime.getRuntime()开启进程来执行脚本文件
Java代码如下:
//导入读取文件的包
import java.io.BufferedReader;
import java.io.InputStreamReader;
//定义类名
public class JavaConPython{
//主函数入口
public static void main(String[] args) {
//定义新的字符串
String[] arguments = new String[] {"python", "E:\\练习\\python\\单词反转.py"};
try {
//执行命令调用程序
Process process = Runtime.getRuntime().exec(arguments);
//取得命令结果的输出流,用一个读输出流类去读,用缓冲器读行
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
////直到读完为止
while ((line = in.readLine()) != null) {
System.out.println(line);
}
in.close();
//调用Process.waitFor()来等待命令执行结束,获取执行结果
int re = process.waitFor();
System.out.println(re);
//抛出异常
} catch (Exception e) {
e.printStackTrace();
}
}
}
4、实现结果
python中运行的结果:
eclipse中运行的结果:
在此需要注意的一点,java代码中的process.waitFor()返回值为0表示我们调用python脚本成功,返回值为1表示调用python脚本失败,这和我们通常意义上见到的0与1定义正好相反。