Run cmd file linux sh windows bat - Java Native OS

Java examples for Native OS:Linux

Description

Run cmd file linux sh windows bat

Demo Code


import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;

public class Main{
    public static void main(String[] argv) throws Exception{
        String filePath = "java2s.com";
        exeuteCmdFile(filePath);/*w w w.  java  2s. c  om*/
    }
    
    public static void exeuteCmdFile(String filePath) {
        try {
            Runtime run = Runtime.getRuntime();
            Process pro = run.exec(filePath);
            // ??file
            FileUtil.deleteFile(filePath.replace("\"", ""));

            BufferedReader br = null;
            StringBuffer sb = new StringBuffer();
            InputStreamReader isr = new InputStreamReader(
                    pro.getInputStream(), "utf-8");
            br = new BufferedReader(isr);
            String line = br.readLine();
            while (line != null) {
                sb.append(line + "\r\n");
                line = br.readLine();
                System.err.println(line);
            }

            try {
                pro.waitFor();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                try {
                    if (br != null) {
                        br.close();
                        br = null;
                    }
                    if (isr != null) {
                        isr.close();
                        isr = null;
                    }
                    if (pro != null) {
                        pro.destroy();
                        pro = null;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Related Tutorials