Java代码执行python代码----Runtime

在Java中, 如果需要调用第三方程序,可以直接通过Runtime实现,这也是最直接最粗暴的做法。

package testJavaUsePython;
import java.io.*;
//自动导包:alt+enter
public class test {
	public static void main(String[] args) throws IOException, InterruptedException {
		String line ;
		String exe = "python";
		String command = "D:\\softWare\\Python\\pythonrun\\BYSJ\\transE-master\\testDataTrue.py";
		String num1 = "1";
		String num2 = "2";
		String[] cmdArr = new String[] {exe, command};
		Process process = Runtime.getRuntime().exec(cmdArr);
		InputStream is = process.getInputStream();
		DataInputStream dis = new DataInputStream(is);
		while ((line = dis.readLine()) != null) {
//            line = decodeUnicode(line);
			System.out.println(line);
		}
		process.waitFor();
	}
	//String command = "D:\\softWare\\Python\\pythonrun\\BYSJ\\transE-master\\testDataTrue.py";
}

有两点需要注意:

一、python程序中不能含有中文,否则输出到Java的控制台shan上可能会是luan乱码

二、python代码使用的文件路径一定要决定路径,不然Java代码是无法执行python代码的;

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值