Run Linux Command - Java Native OS

Java examples for Native OS:Linux

Description

Run Linux 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 commond = "java2s.com";
        String newLine = "java2s.com";
        System.out.println(Linux(commond, newLine));
    }/*from   w  ww. j  a va 2s .c  o m*/

    private static String Linux(String commond, String newLine) {
        BufferedReader bufferedReader = null;
        Process process = null;
        try {
            process = Runtime.getRuntime().exec(commond);
            bufferedReader = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
            String line = null;
            StringBuffer tmp = new StringBuffer();
            while ((line = bufferedReader.readLine()) != null) {
                tmp.append(line).append(newLine);
            }
            return tmp.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null) {
                    bufferedReader.close();
                }
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            bufferedReader = null;
            process = null;
        }

        return "Bad Commond!";
    }
}

Related Tutorials