你好,游客 登录 注册 搜索
背景:
阅读新闻

Android之应用中执行Linux命令

[日期:2013-03-20] 来源:Linux社区  作者:weidi1989 [字体:大 中 小]

Android之应用中执行Linux命令

下面,我以修改某一文件的权限为777为例:

/** 执行Linux命令,并返回执行结果。 */ 
      public static String exec(String[] args) { 
          String result = ""; 
          ProcessBuilder processBuilder = new ProcessBuilder(args); 
          Process process = null; 
          InputStream errIs = null; 
          InputStream inIs = null; 
          try { 
              ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
              int read = -1; 
              process = processBuilder.start(); 
              errIs = process.getErrorStream(); 
              while ((read = errIs.read()) != -1) { 
                  baos.write(read); 
              } 
              baos.write('\n'); 
              inIs = process.getInputStream(); 
              while ((read = inIs.read()) != -1) { 
                  baos.write(read); 
              } 
              byte[] data = baos.toByteArray(); 
              result = new String(data); 
          } catch (IOException e) { 
              e.printStackTrace(); 
          } catch (Exception e) { 
              e.printStackTrace(); 
          } finally { 
              try { 
                  if (errIs != null) { 
                      errIs.close(); 
                  } 
                  if (inIs != null) { 
                      inIs.close(); 
                  } 
              } catch (IOException e) { 
                  e.printStackTrace(); 
              } 
              if (process != null) { 
                  process.destroy(); 
              } 
          } 
          return result; 
      } 

下面在我们需要的地方调用上面函数即可:

String[] args = { "chmod", "777", "(文件路径)"}; 
 exec(args);

更多Android相关信息见Android 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=11

linux
相关资讯       Android Linux命令  Android 执行命令 
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款