从Java代码调用Python文件并获取结果时出错

时间:2017-11-08 06:04:36

标签: java python error-handling jython

我必须使用Java中python执行代码的结果。 我已经下载了jython jar。 我从Internet获取以下部分代码。 但错误反映是   python:无法打开文件' IBM.py':[Errno 2]没有这样的文件或目录它在哪里搜索文件? 我的文件是在pycharm项目中创建的。

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class CallPython {

    /**
 * @param args
 * @throws IOException 
 */
public static void main(String[] args) throws IOException {
     String s = null;
    // TODO Auto-generated method stub
    Process p = Runtime.getRuntime().exec("python IBM.py");
    System.out.println("ayush");
     BufferedReader stdInput = new BufferedReader(new 
             InputStreamReader(p.getInputStream()));

        BufferedReader stdError = new BufferedReader(new 
             InputStreamReader(p.getErrorStream()));

        // read the output from the command
        System.out.println("Here is the standard output of the command:\n");
        while ((s = stdInput.readLine()) != null) {
            System.out.println(s);
        }

        // read any errors from the attempted command
        System.out.println("Here is the standard error of the command (if any):\n");
        while ((s = stdError.readLine()) != null) {
            System.out.println(s);
        }
}}

1 个答案:

答案 0 :(得分:1)

您的IBM.py文件位于pycharm projects文件夹中,并且java代码正在java代码所在的项目文件夹中查找IBM.py文件,这就是它给出错误的原因。

如果您在任何IDE中创建了Java项目,则将文件 IBM.py 复制并粘贴到java项目文件夹中,然后运行此代码,它将正确执行。 :)

如果您只有一个CallPython.java文件并且您没有在任何IDE上的Java Project中创建它,那么将IBM.py粘贴到CallPython.java所在的同一文件夹中。