Java Shell Command runCommand(String command, String args, String file)

Here you can find the source of runCommand(String command, String args, String file)

Description

run Command

License

Open Source License

Declaration

private static boolean runCommand(String command, String args, String file) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.IOException;

import java.util.ArrayList;
import java.util.List;

public class Main {
    private static boolean runCommand(String command, String args, String file) {

        logOut("Trying to exec:\n   cmd = " + command + "\n   args = " + args + "\n   %s = " + file);

        String[] parts = prepareCommand(command, args, file);

        try {/*from  w  w w  . ja v a2 s. c  om*/
            Process p = Runtime.getRuntime().exec(parts);
            if (p == null)
                return false;

            try {
                int retval = p.exitValue();
                if (retval == 0) {
                    logErr("Process ended immediately.");
                    return false;
                } else {
                    logErr("Process crashed.");
                    return false;
                }
            } catch (IllegalThreadStateException itse) {
                logErr("Process is running.");
                return true;
            }
        } catch (IOException e) {
            logErr("Error running command.", e);
            return false;
        }
    }

    private static void logOut(String msg) {
        System.out.println(msg);
    }

    private static String[] prepareCommand(String command, String args, String file) {

        List<String> parts = new ArrayList<>();
        parts.add(command);

        if (args != null) {
            for (String s : args.split(" ")) {
                s = String.format(s, file); // put in the filename thing

                parts.add(s.trim());
            }
        }

        return parts.toArray(new String[parts.size()]);
    }

    private static void logErr(String msg, Throwable t) {
        System.err.println(msg);
        t.printStackTrace();
    }

    private static void logErr(String msg) {
        System.err.println(msg);
    }
}

Related

  1. runCommand(final ProcessBuilder command)
  2. runCommand(String cmd)
  3. runCommand(String cmd)
  4. runCommand(String command)
  5. runCommand(String command)
  6. runCommand(String command[])
  7. runCommand(String program, ArrayList args)
  8. runCommand(String s)
  9. runCommand(String[] args)