当前位置:编程学习 > JAVA >>

JAVA代码执行shell命令 并解析

在Android可能有的系统信息没有直接提供API接口来访问,为了获取系统信息时我们就要在用shell指令来获取信息,这时我们可以在代码中来执行命令 ,这里主要用到ProcessBuilder 这个类.
 
 
代码部分  :
[java]
package com.yin.system_易做图ysis; 
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 ; 
        } 
    } 



补充:软件开发 , Java ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,