网址:“https://www.webmasterworld.com/linux/3613813.htm”
我的测试代码:
1 Button btnShellCommand01 = (Button)findViewById(R.id.btnShellCommand01); 2 btnShellCommand01.setOnClickListener(new View.OnClickListener() 3 { 4 @Override 5 public void onClick(View v) 6 { 7 // https://www.webmasterworld.com/linux/3613813.htm 8 File file = new File("/bin"); 9 MsgAppendLn02("file : "+file.toString());10 if (file.exists())11 MsgAppendLn02(file.toString() + " exists");12 else13 MsgAppendLn02(file.toString() + " not exists");14 //Log.i("zzz", file);15 Process process = null;16 MsgAppendLn02("01");17 try18 {19 //process = Runtime.getRuntime().exec("/bin/bash", null, file);// no such file or directory20 process = Runtime.getRuntime().exec("/system/bin/sh", null, file);21 }22 catch(Exception ex)23 {24 StringWriter sw = new StringWriter();25 PrintWriter pw = new PrintWriter(sw);26 ex.printStackTrace(pw);27 String strStackTrace = sw.toString();28 MsgAppendLn02(strStackTrace);29 }30 MsgAppendLn02("02");31 if (process != null)32 {33 MsgAppendLn02("03");34 BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));35 PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(process.getOutputStream())), true);36 37 out.println("cd ..");38 out.println("pwd");39 out.println("exit");40 try41 {42 MsgAppendLn02("04");43 String line;44 while((line = in.readLine()) != null)45 {46 MsgAppendLn02(line);47 }48 process.waitFor();49 in.close();50 out.close();51 process.destroy();52 53 MsgAppendLn02("05");54 }55 catch(Exception ex)56 {57 StringWriter sw = new StringWriter();58 PrintWriter pw = new PrintWriter(sw);59 ex.printStackTrace(pw);60 String strStackTrace = sw.toString();61 MsgAppendLn02(strStackTrace);62 }63 } // if64 65 Toast.makeText(MainActivity.this, "Shell Command 01 finish .", Toast.LENGTH_SHORT).show();66 }67 }); // btnShellCommand01
网页内容保存于:百度云 CodeSkill33 --> “ > > Java_Linux” --> Java_bash_command_Linux__Work
X