JAVA代碼執行shell命令 並解析 – JAVA編程語言程序開發技術文章

在Android可能有的系統信息沒有直接提供API接口來訪問,為瞭獲取系統信息時我們就要在用shell指令來獲取信息,這時我們可以在代碼中來執行命令 ,這裡主要用到ProcessBuilder 這個類.
 
 
代碼部分  :
[java]
package com.yin.system_analysis; 
import java.io.File; 
import java.io.IOException; 
import java.io.InputStream; 
import android.app.Activity; 
import android.os.Bundle; 
import android.util.Log; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.TextView; 
public class MainActivity extends Activity { 
    private final static String[] ARGS = {"ls","-l"}; 
    private final static String TAG = "com.yin.system"; 
    Button mButton; 
    TextView myTextView; 
    public void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.main); 
        mButton = (Button) findViewById(R.id.myButton); 
        myTextView = (TextView) findViewById(R.id.textView); 
         
        mButton.setOnClickListener(new OnClickListener() { 
             
            public void onClick(View v) { 
                 
                myTextView.setText(getResult()); 
            } 
        }); 
    } 
    public String getResult(){ 
         ShellExecute cmdexe = new ShellExecute ( ); 
         String result=""; 
         try { 
            result = cmdexe.execute(ARGS, "/"); 
        } catch (IOException e) { 
            Log.e(TAG, "IOException"); 
            e.printStackTrace(); 
        } 
        return result; 
    } 
    private class ShellExecute { 
        /*
         * args[0] : shell 命令  如"ls" 或"ls -1";
         * args[1] : 命令執行路徑  如"/" ;
         */ 
        public String execute ( String [] cmmand,String directory) 
        throws IOException { 
        String result = "" ; 
        try { 
        ProcessBuilder builder = new ProcessBuilder(cmmand); 
         
        if ( directory != null ) 
        builder.directory ( new File ( directory ) ) ; 
        builder.redirectErrorStream (true) ; 
        Process process = builder.start ( ) ; 
         
        //得到命令執行後的結果 
        InputStream is = process.getInputStream ( ) ; 
        byte[] buffer = new byte[1024] ; 
        while ( is.read(buffer) != -1 ) { 
        result = result + new String (buffer) ; 
        } 
        is.close ( ) ; 
        } catch ( Exception e ) { 
            e.printStackTrace ( ) ; 
        } 
        return result ; 
        } 
    } 

發佈留言