简体   繁体   中英

Runtime.getRuntime().exec not finding file in java environment

I started a project in Processing and then found that I needed more functionality. I had the following function that worked fine in Processing but now in the java environment I am getting an error.

Function:

void camSummary() {
        System.out.format("Cam summary");
          String commandToRun = "./camSummary.sh"; 
          File workingDir = new File(main.path);
          try {

            Process p = Runtime.getRuntime().exec(commandToRun, null, workingDir);
            int i = p.waitFor();
            if (i==0) {
              BufferedReader stdInput = new BufferedReader(new InputStreamReader(p.getInputStream()));
              while ( (returnedValues = stdInput.readLine ()) != null) {
                  System.out.format(returnedValues);
              }
            }
          }
          catch(Throwable t) {
              System.out.format("error: " + t + "\n");  
          }
        }

Error:

Cannot run program "camSummary.sh" (in directory "/Users/lorenzimmer/Documents/RC/CamSoft/ "): error=2, No such file or directory

I've found that there have been some very slight differences from processing to java. I'm wondering if this function just needs to be tweaked slightly to run properly.

Any help would be greatly appreciated.

Loren

Runtime.exec does not invoke a shell, so you have to explicitly invoke one (bash, sh, etc)

Try this:

Change String commandToRun = "./camSummary.sh";

to

String[] commandToRun = {"bash", "-c", "/path/to/camSummary.sh"};

or

String[] commandToRun = {"sh", "/path/to/camSummary.sh"};

Then change

Process p = Runtime.getRuntime().exec(commandToRun, null, workingDir);

to

Process p = Runtime.getRuntime().exec(commandToRun);

In one line: Process p = Runtime.getRuntime().exec(new String[] {"bash", "-c", "/path/to/script"});

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