简体   繁体   中英

java executing shell commands

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:

 private static void shell(String cmd)
 {
   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.

I think you are passing the command string as some mkdir command like , "mkdir C:\\some\\folder\\path".

mkdir is not some binary in Windows path, it's a parameter to command line. Use the command string as "cmd.exe /c mkdir C:\\some\\folder\\path"

Then it should work fine.

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:

 private static void shell(String cmd)
 {
   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.

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