如果要在java程序里执行一条linux可以用下面的写法,android中也类似

Java代码
  1. Processprocess=Runtime.getRuntime().exec(cmd);
  2. process.waitFor(); //让该process 阻塞

但是当遇到像cd这样的命令时,上面的这种写法切不管用,很多时候我们以为是命令输错了或是文件找不到。

现在提供一种新的执行命令方法:

Process proc = null;try {proc = Runtime.getRuntime().exec("/system/bin/sh", null, new File("/system/bin")); // android中使用// proc = Runtime.getRuntime().exec("/bin/bash", null, new File("/bin")); //Linux中使用// 至于windows,由于没有bash,和sh 所以这种方式可能行不通Log.d("","");} catch (IOException e) {e.printStackTrace();}if (proc != null) {BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);out.println("cd /data/data/com.vatata.atest.commandexecute");out.println("pwd");out.println("pwd");out.println("pwd");out.println("cd /");out.println("ls -l");// out.println("exit");try {String line;while ((line = in.readLine()) != null) {System.out.println(line);Log.d("command", line);}// proc.waitFor(); //上面读这个流食阻塞的,所以waitfor 没太大必要性in.close();out.close();proc.destroy();} catch (Exception e) {e.printStackTrace();}}

附上源码吧,可以看看,希望对需要的人有点帮助 <!--EndFragment-->

更多相关文章

  1. Android预安装软件&adb命令&编译源码
  2. Android 命令行编译、打包生成apk文件
  3. Android执行shell命令
  4. android中json文件的写法
  5. 【【【常用的ubuntu第三方工具及android命令(自存档)】】】二
  6. android 命令(adb shell)进入指定模拟器或设备
  7. 工作环境搭建(8) - CentOS7命令行安装Android SDK
  8. [android]android性能测试命令行篇
  9. Android 开发者该学点Linux 命令了

随机推荐

  1. 安卓动画(Animation使用)
  2. android studio 最新3.0 kotlin与databin
  3. ScrollView嵌套ViewPager,ViewPager内容
  4. SQLite数据库相关(三) SQLiteOpenHelper类
  5. android contacts 联系人搜索解析
  6. Activity的Launch Mode
  7. Android四大组件之ContentProvider
  8. Chromium进程间的通信机制浅析(android版
  9. Link方式安装ADT
  10. Android中contentProvider的用途