Android 应用中执行cd命令

1 篇文章 0 订阅
1 篇文章 0 订阅

 

如果要在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();
			}
		}
 

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

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值