java调用cmd

没有太多需要说的,

IO部分掌握的不好啊,期间遇到了乱码问题......这里要mark一下,有时间一定要搞定它。

下面直接上代码:

package RuntimeTest.RuntimeTest;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

/**
 * Hello world!
 *
 */
public class App 
{
    public static void main( String[] args ) throws IOException
    {

        Runtime r=Runtime.getRuntime();
        Process p=r.exec("cmd /c S: && dir && mkdir hello");//执行多条语句,用&&连接
        InputStream is=p.getInputStream();

        BufferedInputStream bis=new BufferedInputStream(is);
        
        byte b[]=new byte[1024];
        String line;
        
        //~
        File f=new File("S:\\f.txt");
        OutputStream os=new FileOutputStream(f);
        BufferedOutputStream bos=new BufferedOutputStream(os);
        
        //~
        
        while(-1!=bis.read(b)){
            line=new String(b,"GBK");//这里不用gbk的话,控制台打印的是乱码......愁~
            bos.write(b);//将结果写到txt里
            System.out.println(line);
        }
        
        bis.close();
        is.close();
        bos.close();
        os.close();
        
    }
}

其实cmd或者shell什么的还是很好用的。

很多东西不一定非要用java解决,配合上shell之类的还是很好的。

就是不知道效率怎么样。

嗯,类似的还有JNI。

 

posted @ 2014-08-24 11:46  oh~NO!  阅读(482)  评论(0编辑  收藏  举报