execute Windows Command - Java Native OS

Java examples for Native OS:Windows

Description

execute Windows Command

Demo Code


//package com.java2s;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main {
    public static void main(String[] argv) throws Exception {
        String cmd = "java2s.com";
        System.out.println(exec(cmd));
    }/*from   www.  j a v  a2s.c o m*/

    public static String exec(String cmd) {
        return exec(cmd, "GBK");
    }

    public static String exec(String cmd, String encoding) {
        BufferedReader br = null;
        StringBuilder sb = new StringBuilder();
        try {
            Process p = Runtime.getRuntime().exec("cmd.exe /c " + cmd);

            br = new BufferedReader(new InputStreamReader(
                    p.getInputStream(), encoding));
            String line = null;
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }

            br = new BufferedReader(new InputStreamReader(
                    p.getErrorStream(), encoding));
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            sb.insert(0, "exitValue:" + p.exitValue() + "\n");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sb.toString();
    }
}

Related Tutorials