Java ProcessBuilder Cannot Find File Specified

痞子三分冷 提交于 2020-02-07 09:59:39

问题


import java.io.*;
class RunTest {
public static void main(String a[]) {
    try {
        String prg = "import sys\nprint int(sys.argv[1])+int(sys.argv[2])\n";
        BufferedWriter out = new BufferedWriter(new FileWriter("test1.py"));
        out.write(prg);
        int number1 = 1;
        int number2 = 2; 
        ProcessBuilder pb = new ProcessBuilder("python","test1.py",""+number1,""+number2);
        Process p = pb.start();
        BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
        int ret = new Integer(in.readLine()).intValue();
        System.out.println("value is : "+ret);
    } catch(Exception e) {
        e.printStackTrace();
    }
}

}

When I run this code (I'm using Eclipse), I get the stack trace:

java.io.IOException: Cannot run program "python": CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessBuilder.start(ProcessBuilder.java:1048) at RunTest.main(RunTest.java:11) Caused by: java.io.IOException: CreateProcess error=2, The system cannot find the file specified at java.lang.ProcessImpl.create(Native Method) at java.lang.ProcessImpl.(ProcessImpl.java:386) at java.lang.ProcessImpl.start(ProcessImpl.java:137) at java.lang.ProcessBuilder.start(ProcessBuilder.java:1029) ... 1 more

Anyone have any idea why and what I can do?

Thanks!


回答1:


You have to flush() and you should close() (which will also flush()) after you write to the File.

out.write(prg);
out.close(); // <-- add this.

Also, you'll need to add python to your PATH.




回答2:


Sorry, this is probably really unhelpful, but somehow, it just started working. No idea why or how, because I haven't changed anything. Eclipse basically just restarted itself randomly and now it works! Sorry I couldn't post a solution that will help others, but thanks anyway for your help @MadProgrammer and @Elliott !



来源:https://stackoverflow.com/questions/28204342/java-processbuilder-cannot-find-file-specified

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!