Running Bash commands in Java

后端 未结 7 1288
名媛妹妹
名媛妹妹 2020-11-30 06:03

I have the following class. It allows me to execute commands through java.

public class ExecuteShellCommand {

public String executeCommand(String command) {         


        
7条回答
  •  独厮守ぢ
    2020-11-30 06:26

    for future reference: running bash commands after cd , in a subdirectory:

    import java.io.BufferedReader;
    import java.io.InputStreamReader;
    
    /*
    
    $ ( D=somewhere/else ; mkdir -p $D ; cd $D ; touch file1 file2 ; )
    $ javac BashCdTest.java && java BashCdTest
     .. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file1
     .. stdout: -rw-r--r-- 1 ubuntu ubuntu 0 Dec 28 12:47 file2
     .. stderr: /bin/ls: cannot access isnt_there: No such file or directory
     .. exit code:2
    
    */
    class BashCdTest
        {
        static void execCommand(String[] commandArr)
            {
            String line;
            try
                {
                Process p = Runtime.getRuntime().exec(commandArr);
                BufferedReader stdoutReader = new BufferedReader(new InputStreamReader(p.getInputStream()));
                while ((line = stdoutReader.readLine()) != null) {
                    // process procs standard output here
                    System.out.println(" .. stdout: "+line);
                    }
                BufferedReader stderrReader = new BufferedReader(new InputStreamReader(p.getErrorStream()));
                while ((line = stderrReader.readLine()) != null) {
                    // process procs standard error here
                    System.err.println(" .. stderr: "+line);
                    }
                int retValue = p.waitFor();
                System.out.println(" .. exit code:"+Integer.toString(retValue));
                }
            catch(Exception e)
                { System.err.println(e.toString()); }
            }
    
        public static void main(String[] args)
            {
            String flist = "file1 file2 isnt_there";
            String outputDir = "./somewhere/else";
            String[] cmd = {
                "/bin/bash", "-c",
                "cd "+outputDir+" && /bin/ls -l "+flist+" && /bin/rm "+flist
                };
            execCommand(cmd);
            }
        }
    

提交回复
热议问题