Java method of executing Linux commands

  • 2020-04-01 03:34:19
  • OfStack

This article illustrates how Java executes Linux commands. Share with you for your reference. The specific implementation method is as follows:


public class StreamGobbler extends Thread { 
     
    InputStream is; 
    String type; 
 
    public StreamGobbler(InputStream is, String type) { 
        this.is = is; 
        this.type = type; 
    } 
 
    public void run() { 
        try { 
            InputStreamReader isr = new InputStreamReader(is); 
            BufferedReader br = new BufferedReader(isr); 
            String line = null; 
            while ((line = br.readLine()) != null) { 
                if (type.equals("Error")) { 
                    System.out.println("Error   :" + line); 
                } else { 
                    System.out.println("Debug:" + line); 
                } 
            } 
        } catch (IOException ioe) { 
            ioe.printStackTrace(); 
        } 
    } 

private void shell(String cmd)
{
        String[] cmds = { "/bin/sh", "-c", cmd };
        Process process;         try
        {
            process = Runtime.getRuntime().exec(cmds);             StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "Error");
            StreamGobbler outputGobbler = new StreamGobbler(process.getInputStream(), "Output");
            errorGobbler.start();
            outputGobbler.start();
            try
            {
                process.waitFor();
            }
            catch (InterruptedException e)
            {
                e.printStackTrace();
            }
        }
        catch (IOException e)
        {
            e.printStackTrace();
        }
}

Where the parameter CMD is the Linux command. Only one command can be executed at a time.

1.Java runtime. exec()

Always read the stream before calling the waitFor() method
Always read from the standard error stream, and then read from the standard output stream

2. The best way to execute system commands is to write a bat file or shell script.

I hope this article has been helpful to your Java programming.


Related articles: