1

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.

4
  • You mean the shell script expects input on STDIN? BTW I'd be surprised if "su" worked like this. It really only takes the password from the actual terminal (or the command line). I found a solution to this (making Java "su" a copy of itself) if that's what you want. Commented Dec 4, 2017 at 15:26
  • Did you see the public an free online documentation? docs.oracle.com/javase/7/docs/api/index.html?java/util/… Commented Dec 4, 2017 at 15:28
  • I think link is wrong it direct me to Locale.class Commented Dec 4, 2017 at 15:40
  • Could you run your task using sudo instead of su? Commented Dec 4, 2017 at 15:55

2 Answers 2

2

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;
    }
}
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

2 Comments

no, I don't want to just run a shell file as I said my shell gets two kinds of arguments on before execute and another after executing shell file and my problem is the second type. how can I put argument after running shell
what do you mean by argument after running shell?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.