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