简体   繁体   中英

Weird runtime.exec() exception

I'm running Eclipse on Windows 7 (also happens on XP). As you see below, the path stays the same, only it's not found using the second technique (which I need to use).

This works:

Runtime runtime = Runtime.getRuntime();

    // Start street processes
    for (int i=0; i < NUM_STREETS; i++) {

        Process process = runtime.exec("java -classpath \\bin trafficcircle.Street");

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        while ((line = br.readLine()) != null && !line.isEmpty()) {
            System.out.println(line);
        }
    }

But this doesn't:

Runtime runtime = Runtime.getRuntime();
String[] cmdAndArgs = {"java -classpath \\bin trafficcircle.Street",
            "",
            "" };

    // Start street processes
    for (int i=0; i < NUM_STREETS; i++) {
        Process process = runtime.exec(cmdAndArgs);

        InputStream is = process.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);
        String line;

        while ((line = br.readLine()) != null && !line.isEmpty()) {
            System.out.println(line);
        }
    }

And produces the following exception. Why? Thanks.

java.io.IOException: Cannot run program "java -classpath \bin trafficcircle.Street": CreateProcess error=2, The system cannot find the file specified
    at java.lang.ProcessBuilder.start(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at java.lang.Runtime.exec(Unknown Source)
    at trafficcircle.Main.runConfig(Main.java:81)
    at trafficcircle.Main.main(Main.java:20)
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.<init>(Unknown Source)
    at java.lang.ProcessImpl.start(Unknown Source)
    ... 5 more

I think you need to put the args seperately. Otherwise its going to look for an exe called java -classpath... . So something like

String[] cmdAndArgs = {"java",
        "-classpath",
        "\\bin",
        "trafficcircle.Street" };

To pass additional args just include them in the array

String arg1 = ...;
String arg2 = ...;
String[] cmdAndArgs = {"java",
        "-classpath",
        "\\bin",
        "trafficcircle.Street",
        arg1,
        arg2 };

如果你没有传递更多的论点,你可以尝试,

String[] cmdAndArgs = {"java -classpath \\bin trafficcircle.Street"}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM