I am writing a java program that needs to execute shell commands, so I wrote a function that would take the command to execute as a string (ie: "mkdir ~/Folder1") and execute that command with the shell. Here is the function:

   try
   {
    Runtime run = Runtime.getRuntime();
    Process pr = run.exec(cmd);
    pr.waitFor();
    BufferedReader buf = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line = "";

    while ((line = buf.readLine()) != null) {
     System.err.println(line); // show any errors returned by the command executed on the error console

    }

   } catch (Exception ee) {}

for some weird reason this function is not executing any commands. Did I do this wrong? It seems like a simple thing to execute shell commands, but it is not working.

First thing is to fix that terrible catch clause.
If/when there is an error you just told Java that you didn't want to know anything about it, and please discard the detailed error message that Java just created for you.
ALWAYS put an e.printStackTrace(); in your catch blocks until/unless you have a good reason to do something else.

Second thing: You read the standard output from your Process, but you ignore its error stream, so you won't see any error messages it generates. Best to read/display that as well.

There's a good chance that these two things will give you the info you need.

Last thing: Runtime.exec was replaced over 10 years ago by ProcessBuilder, which is much more powerful and avoids many problems. You should replace this code with the ProcessBuilder equivalent. Google for details and examples.

Edited 5 Days Ago by JamesCherrill

oh ok, I will definitely print the stacktrace from now on.

cmd = "mkdir ~/Desktop/yellow/home"

    InputStream is = null;
    ByteArrayOutputStream baos = null;
    ArrayList<String> commands = new ArrayList<String>( Arrays.asList(cmd.split(" ") ) );

    ProcessBuilder pb = new ProcessBuilder(commands);
    try {
        Process prs = pb.start();
        is = prs.getInputStream();
        byte[] b = new byte[1024];
        int size = 0;
        baos = new ByteArrayOutputStream();
        while((size = is.read(b)) != -1){
            baos.write(b, 0, size);
        }
        System.out.println(new String(baos.toByteArray()));
    } 
    catch (IOException e) 
    {
        e.printStackTrace();
    } 
    finally
    {
        try {
            if(is != null) is.close();
            if(baos != null) baos.close();
        } catch (Exception ex){}
    }
}

Output from this is blank.I am just trying to tell my program to execute the command in 'cmd'. Why is this still not working?

I will definitely print the stacktrace from now on.
See line 26

You're still not displaying the Process's error stream - which is where error messages may be waiting. (all you need is a pb.redirectErrorStream();)

Which OS are you using?

ps Just a question: Why all the faffing about with a byte array stream?

Edited 4 Days Ago by JamesCherrill