Java ProcessBuilder Cannot Find File Specified

2019-09-02 12:02发布

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!

2条回答
姐就是有狂的资本
2楼-- · 2019-09-02 12:49

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.

查看更多
不美不萌又怎样
3楼-- · 2019-09-02 12:55

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 !

查看更多
登录 后发表回答