Question

I'm using this code to make my Java program open a (visible) CMD window:

try {
            String line;
            Process p = Runtime.getRuntime().exec("cmd /C start \"Render\" \"" + myPath + "\\punchRender.cmd\"");
             BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
            System.out.println(line);
            jLabel7.setText(line);

            }
            input.close();
        } catch (Exception err) {
            err.printStackTrace();
        }

and I've been trying to do the same thing with the OSX terminal, this is where I'm at right now:

  try {
            String line;
            Process p = Runtime.getRuntime().exec("sh " + myPath + "/punchRender.sh");
             BufferedReader input =
                    new BufferedReader(new InputStreamReader(p.getInputStream()));
            while ((line = input.readLine()) != null) {
            System.out.println(line);
            jLabel7.setText(line);

            }
            input.close();
        } catch (Exception err) {
            err.printStackTrace();
        }

So far, no luck :( Any suggestions? The .sh file isn't even running...

Was it helpful?

Solution

I would just make sure your shell script has the execute bits on and just pass in the shell script file name.

Process p = Runtime.getRuntime().exec(myPath + "/punchRender.sh")

Edit:

I don't know Java specifically if there is anyway to set file permissions for Unix/Linux with it to set the eXecute bit or how to escape quotes. But It would be something like this:

Process chmod = Runtime.getRuntime().exec("chmod u+x \"" + myPath + "/punchRenderer.sh\"")

OTHER TIPS

This should work. Not only running the script, but opening a terminal also:

Process p = Runtime.getRuntime().exec("open -a /Applications/Utilities/Terminal.app \"" + myPath + " /punchRender.sh\"");

If you want a new visible Terminal window, you can't run the shell directly. You need to start Terminal and then run a .command file, not a shell script. I'm not sure how hard it would be to connect the stdout of that command to your Java process. You might have to figure out some other way of getting the output into the terminal.

By the way, I tried your code in a class on my own Mac at home, and it ran a .sh file just fine. I was running the java class from the command line. Maybe sh just isn't in your PATH.

I assume you've checked that the .sh file is executable, haven't you?

Can I suggest you capture the standard error as well as the standard output, and dump that. That should give you some idea as to what's going on (it's good practise generally).

You may need to gather standard output and standard error in different threads to avoid blocking issues. See here for a StreamGobbler

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top