max
max

Reputation: 6187

Run a shell file in java

In Java you can call a shell file like this:

public class Shell {
    private static Shell rootShell = null;
    private final Process proc;
    private final OutputStreamWriter writer;

    private Shell(String cmd) throws IOException {
        this.proc = new ProcessBuilder(cmd).redirectErrorStream(true).start();
        this.writer = new OutputStreamWriter(this.proc.getOutputStream(), "UTF-8");
    }

    public void cmd(String command)  {
        try {
            writer.write(command+'\n');
            writer.flush();
        } catch (IOException e) {   }
    }

    public void close() {
        try {
            if (writer != null) {  
                writer.close();
                if(proc != null) {  
                    proc.destroy();
                }
            }
        } catch (IOException ignore) {}
    }

    public static void exec(String command) {
        Shell.get().cmd(command);   
    }

    public static Shell get() {
        if (Shell.rootShell == null) {
            while (Shell.rootShell == null) {
                try {   
                    Shell.rootShell = new Shell("su"); //Open with Root Privileges 
                } catch (IOException e) {   }
            }
        } 
        return Shell.rootShell;
    }
}

Shell.exec("echo " + bt.getLevel() + " > "+ flashfile);     

right.
but I have a shell which giving an argument after executing it.
how can I pass that argument? I don't want user type anything to run this shell file. in another word, I want to fully automate a shell file.

Upvotes: 1

Views: 169

Answers (2)

gil.fernandes
gil.fernandes

Reputation: 14621

If you want to automate a shell file with a Java programme, this can be done. You could even pipe a series of commands to this programme saved in a file and executing these as a batch.

You can execute commands batches of commands from like this:

java -cp experiments-1.0-SNAPSHOT.jar ConsoleReader < commands.txt

commands.txt is a file with a series of commands:

cmd /k date
cmd /k dir
netstat
ipconfig

Or you can with the same programme allow the user to execute commands on the command line.

Below you can find a sample programme which you can compile and be run in the above described manner.

What does it do?

  1. It hooks a java.util.Scanner to the console input and consumes each line.
  2. Then it spawns two threads which listen to the error and input streams and write out either to stderr or stdin.
  3. Empty lines on the console are ignored
  4. If you type "read " it will execute the commands on that file.

Source:

public class ConsoleReader {

    public static void main(String[] args) throws IOException, DatatypeConfigurationException {
        try(Scanner scanner = new Scanner(new BufferedInputStream(System.in), "UTF-8")) {
            readFromScanner(scanner);
        }
    }

    private static final Pattern FILE_INPUT_PAT = Pattern.compile("read\\s*([^\\s]+)");

    private static void readFromScanner(Scanner scanner) {
        while (scanner.hasNextLine()) {
            try {
                String command = scanner.nextLine();
                if(command != null && !command.trim().isEmpty()) {
                    command = command.trim();
                    if("exit".equals(command)) {
                        break; // exit shell
                    }
                    else if(command.startsWith("read")) { // read from file whilst in the shell.
                        readFile(command);
                    }
                    else {
                        Process p = Runtime.getRuntime().exec(command);
                        Thread stdout = readFromStream(p.getInputStream(), System.out, "in");
                        Thread stderr = readFromStream(p.getErrorStream(), System.err, "err");
                        stdout.join(200);
                        stderr.join(200);
                    }
                }
            }
            catch(Exception e) {
                Logger.getLogger("ConsoleReader").log(Level.SEVERE, String.format("Failed to execute command %s", e));
            }
        }
    }

    private static void readFile(String command) throws FileNotFoundException {
        Matcher m = FILE_INPUT_PAT.matcher(command);
        if(m.matches()) {
            String file = m.group(1);
            File f = new File(file);
            if (f.exists()) {
                try (Scanner subScanner = new Scanner(f)) {
                    readFromScanner(subScanner);
                }
            }
        }
        else {
            System.err.printf("Oops, could not find '%s'%n", command);
        }
    }

    private static Thread readFromStream(InputStream stdin, PrintStream out, String name) throws IOException {
        Thread thread = new Thread(() -> {
            try (BufferedReader in = new BufferedReader(new InputStreamReader(stdin))) {
                String line;
                while ((line = in.readLine()) != null) {
                    out.println(line);
                }
            } catch (IOException e) {
                Logger.getLogger("ConsoleReader").log(Level.SEVERE, "Failed to read from stream.", e);
            }
        }, name);
        thread.setDaemon(true);
        thread.start();
        return thread;
    }
}

Upvotes: 2

Tyler
Tyler

Reputation: 203

Runtime.getRuntime().exec("src/[FILE LOCATION]");

I think this is the command you're looking for. Let me know if it works!

Upvotes: 1

Related Questions