execute command - Java Native OS

Java examples for Native OS:Shell Command

Description

execute command

Demo Code


//package com.java2s;
import java.io.*;

public class Main {
    public static void main(String[] argv) throws Exception {
        String cmd = "java2s.com";
        System.out.println(exec(cmd));
    }/* w  ww .j a va 2  s  .  c  o  m*/

    public static String exec(String cmd) {
        StringBuffer sb1;
        StringBuffer sb2;
        sb1 = new StringBuffer();
        sb2 = new StringBuffer();
        String temp1 = "";
        String temp2 = "";
        Runtime rt = Runtime.getRuntime();
        try {
            Process p = rt.exec(cmd);
            BufferedReader bufferedReader1 = new BufferedReader(
                    new InputStreamReader(p.getInputStream()));
            BufferedReader bufferedReader2 = new BufferedReader(
                    new InputStreamReader(p.getErrorStream()));

            while ((temp1 = bufferedReader1.readLine()) != null) {
                sb1.append(temp1);
                System.out.println(temp1);
            }

            while ((temp2 = bufferedReader2.readLine()) != null) {
                sb2.append(temp2);
                System.out.println(temp2);
            }
            p.waitFor();
            return sb1.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return sb1.toString();
    }
}

Related Tutorials