java调用python( 二 )


四、Java调用Python的实例
以下是一个用Java调用Python进行数据分析的实例 。
1.编写Python程序
编写一个简单的Python程序 , 用于生成随机数和计算其平均值 。保存为python_script.py文件 。
```
import random
def generate_numbers():
return [random.randint(1, 100) for _ in range(10)]
def calculate_average(numbers):
return sum(numbers) / len(numbers)
if __name__ == "__main__":
numbers = generate_numbers()
average = calculate_average(numbers)
print("Numbers: ", numbers)
print("Average: ", average)
```
2.编写Java程序
编写一个Java程序 , 用于调用Python程序并获得结果 。如下:
```
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
try {
ProcessBuilder pb = new ProcessBuilder("python", "python_script.py");
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
3.运行Java程序
在命令行中进入Java程序所在目录 , 运行以下命令:
```
javac Main.java
java Main
```
输出结果如下:
```
Numbers:[100, 76, 45, 22, 18, 67, 77, 97, 23, 41]
Average:53.6
```

推荐阅读