加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

读取Runtime.getRuntime().exec()方法返回的结果的代码

(2007-05-30 08:52:21)
标签:

exec

runtime

分类: J2SE
import java.io.*;
import java.util.List;
import java.util.Vector;

public class Execute  {

    private final static int OUTPUT_BUFFER_SIZE = 1024;
    public static void main(String[] args) throws Exception{
    Vector vector = new Vector(1,1);
    vector.add("/bin/ls");
    System.out.println(exec(vector));
    }

    /**
     * Executes a method call.
     *
     * @param arguments a <tt>List</tt> of <tt>String</tt> objects containing
the values
     * of the arguments passed to the method.
     * @return the <tt>TemplateModel</tt> produced by the method, or null.
     * @throws Exception
     */
    public static Object exec (List arguments) throws Exception  {
        String aExecute;
        StringBuffer    aOutputBuffer = new StringBuffer();

        if( arguments.size() < 1 ) {
            throw new Exception( "Need an argument to execute" );
        }

        aExecute = (String)(arguments.get(0));

        try {
            Process exec = Runtime.getRuntime().exec( aExecute );

            // stdout from the process comes in here
            InputStream execOut = exec.getInputStream();
            InputStreamReader execReader = new InputStreamReader( execOut );


            char[] buffer = new char[ OUTPUT_BUFFER_SIZE ];
            int bytes_read = execReader.read( buffer );

            while( bytes_read > 0 ) {
                aOutputBuffer.append( buffer, 0, bytes_read );
                bytes_read = execReader.read( buffer );
            }
        }
        catch( IOException ioe ) {
            throw new Exception( ioe.getMessage() );
        }
        return aOutputBuffer.toString();
    }
}

程序执行结果为:
Execute.class
Execute.java
--

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有