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

Java代码 
  1. Process process = 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();}}
 

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

 

更多相关文章

  1. windows 下 android 使用ant自动打包
  2. android cmd adb命令安装和删除apk应用
  3. android 命令行安装apk
  4. android 命令行安装apk
  5. Android(安卓)9.0 cmds
  6. android中如何执行java命令
  7. Android(安卓)Studio 及日常常用命令
  8. 命令行下创建 Android(安卓)工程,用 Ant 进行编译部署
  9. Android常用命令之创建avd

随机推荐

  1. Android(安卓)JNI入门第三篇——jni头文
  2. 经纬度转度分秒 Java/Android
  3. android 自定义权限
  4. Android(安卓)Studio 配置多个代码仓库(m
  5. android studio 添加外部库的问题
  6. android -------- ConstraintLayout 宽高
  7. Android(安卓)下载文件 显示进度条
  8. Android(安卓)Studio 安装教程
  9. MediaPlayer+Stagefright架构(音频)图解
  10. Warning:The specified Android(安卓)SDK