Java调用命令行
2015-11-16 09:40
295 查看
Runtime.exec() 不等同于直接执行command line命令!
啊,我算是在这里吃了苦头了。Runtime.exec()很有局限性,对有些命令不能直接把command line里的内容当作String参数传给exec().
比如重定向等命令。举个例子:
javap -l xxx > output.txt
这时要用到exec的第二种重载,即input 参数为String[]:
Process p = Runtime.getRuntime().exec(new String[]{“/bin/sh”,”-c”,”javap -l xxx > output.txt”});
获得输出值:
执行命令行获取返回值:
方法一
方法二
附项目实战代码:
啊,我算是在这里吃了苦头了。Runtime.exec()很有局限性,对有些命令不能直接把command line里的内容当作String参数传给exec().
比如重定向等命令。举个例子:
javap -l xxx > output.txt
这时要用到exec的第二种重载,即input 参数为String[]:
Process p = Runtime.getRuntime().exec(new String[]{“/bin/sh”,”-c”,”javap -l xxx > output.txt”});
import java.io.InputStreamReader; import java.io.LineNumberReader; import java.util.ArrayList; import java.util.List; public class test{ /** * 运行shell脚本 * @param shell 需要运行的shell脚本 */ public static void execShell(String shell){ try { Runtime rt = Runtime.getRuntime(); rt.exec(shell); } catch (Exception e) { e.printStackTrace(); } } /** * 运行shell * * @param shStr * 需要执行的shell * @return * @throws IOException */ public static List runShell(String shStr) throws Exception { List<String> strList = new ArrayList(); Process process; process = Runtime.getRuntime().exec(new String[]{"/bin/sh","-c",shStr},null,null); //process = Runtime.getRuntime().exec(shStr); InputStreamReader ir = new InputStreamReader(process .getInputStream()); LineNumberReader input = new LineNumberReader(ir); String line; process.waitFor(); while ((line = input.readLine()) != null){ System.out.println(line); strList.add(line); } return strList; } public static void main(String []arge)throws Exception { test t=new test(); t.runShell("/home/ubuntu/soft/tomcat/bin/startup.sh") }
获得输出值:
执行命令行获取返回值:
方法一
Process p = Runtime.getRuntime().exec("javac"); InputStream is = p.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(is)); String line; while((line = reader.readLine())!= null){ System.out.println(line); } p.waitFor(); is.close(); reader.close(); p.destroy();
方法二
import java.io.BufferedInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; public class TestCmd { public static void main(String[] args) { java.lang.Process process = null; try { process = Runtime.getRuntime().exec("net user"); ByteArrayOutputStream resultOutStream = new ByteArrayOutputStream(); InputStream errorInStream = new BufferedInputStream( process.getErrorStream()); InputStream processInStream = new BufferedInputStream( process.getInputStream()); int num = 0; byte[] bs = new byte[1024]; while ((num = errorInStream.read(bs)) != -1) { resultOutStream.write(bs, 0, num); } while ((num = processInStream.read(bs)) != -1) { resultOutStream.write(bs, 0, num); } String result = new String(resultOutStream.toByteArray()); System.out.println(result); errorInStream.close(); errorInStream = null; processInStream.close(); processInStream = null; resultOutStream.close(); resultOutStream = null; } catch (IOException e) { e.printStackTrace(); } finally { if (process != null) process.destroy(); process = null; } } }
附项目实战代码:
DataOutputStream os = null; private Process process = null; private Handler mCaptureHanlder = new Handler(new Handler.Callback() { @Override public boolean handleMessage(Message msg) { return false; } }); // 开始抓包 private Runnable mCaptureRunnable = new Runnable() { public void run() { if (!TextUtils.isEmpty(ForkConstants.path)) { String commandPath = mContext.getFilesDir().getAbsolutePath() + "/tcpdump"; String permissionCmd = "chmod 777 " + commandPath; try { Runtime.getRuntime().exec(permissionCmd); process = Runtime.getRuntime().exec("su"); os = new DataOutputStream(process.getOutputStream()); os.writeBytes(commandPath + " " + ForkConstants.parameters.trim() + " -w " + ForkConstants.path + "\n"); } catch (Exception e) { e.printStackTrace(); } } } }; // 停止抓包 private Runnable mStopRunnable = new Runnable() { public void run() { if (!TextUtils.isEmpty(ForkConstants.path)) { try { os.writeBytes("kill $(ps | grep tcpdump | tr -s ' ' | cut -d ' ' -f2)\n"); os.writeBytes("killall tcpdump\n"); os.writeBytes("busybox kill $(ps | grep tcpdump | tr -s ' ' | cut -d ' ' -f2)\n"); os.writeBytes("busybox killall tcpdump\n"); os.writeBytes("exit\n"); os.flush(); os.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { try { process.getInputStream().close(); process.getOutputStream().close(); process.destroy(); process = null; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } };
相关文章推荐
- Spring 学习日记(三)Resource接口
- eclipse调试java不能看到变量的值
- Java 日期转毫秒和毫秒转日期
- 源码分析:Java对象的内存分配
- Spring 学习日记(二)BeanFactory小议
- eclipse 离线安装插件
- meclipse中project facet问题
- Spring的核心技术(一)
- Java编程中线程池的基本概念和使用
- JAVASE中JFileChooser的使用小结 打开文件并显示
- JAVA中精确保留到小数点后2(n)位的办法
- 占用内存空间
- 写一方法,打印等长的二维数组,要求从1开始的自然数由方阵的最外圈向内螺旋方式地顺序排列。 如: n = 4 则打印:
- 28人买可乐喝,3个可乐瓶盖可以换一瓶可乐,那么要买多少瓶可乐,够28人喝?假如是50人,又需要买多少瓶可乐?
- Java学习之困
- guava的基本语法整理
- java程序操作xml文件
- 运算符-java
- javaSE基础入门学习笔记1
- 字母数字、字母、汉字验证码 (java)