一颗秋天的树
梦有多远,路就有多远......
posts - 15,comments - 20,trackbacks - 0

使用Runtime调用bat文件处理外部角本时一般使用 Runtime.getRuntime.exec(command)就可以了
如果批处理是使用db2的db2cmd时,dos窗口则会弹出db2命令窗口执行相关的处理角本,如果需要等特此批处理命令执行完成后再执行下面的流程就会出现相应的问题,如下例流程,将客户端将生成数据备份文件上传至服务器

{47BE8604-7CE8-4B36-8C17-B0B98C125E2C}.BMP

因waitFor() 只能控制第一个dos窗口的进程,而无法控制下一个窗口,程序则会同步执行,当数据还没生成时就已经进行压缩处理了,当然会出现错误。
所以在执行批处理时将批出理文件隐式执行

实施方法代码如下

     /**
     * 执行批处理
     * 
@param  command
     
*/

    
public   void  runBat(String command) {
            Process child 
=   null ;
            
try   {
                      Runtime rt
=  Runtime.getRuntime();
                     child
= rt.exec(command);
                        //以下代码为控制台输出相关的批出理
                      String line 
=   null ;
                      BufferedReader reader 
=   new  BufferedReader( new  InputStreamReader(child.getInputStream()));
                      
while ((line  =  reader.readLine())  !=   null )
                      
{
                          System.out.println(line);
                      }

                      reader.close();
                     
// 等待刚刚执行的命令的结束 
 
                  while  ( true )
                        
if (child.waitFor()  ==   0 break ;
                    }
      
            }

            
catch  (Exception ex) {
                   child.destroy();
                ex.printStackTrace();
            }

        }

主程序如下:

public   void  exportBat(String zipPath) {
         
// 执行批处是导出到目录下
           this .runBat( " db2cmd -c -w -i exportdb.bat " );
         
// 压缩文件生成打包
            this.doZip(zipPath ,zipPath +" \\test .rar" ); 
         
  // 上传
          this .ftpUp("目录");
         
// 删除客户端目录生成的文件
          this .delFile(zipPath );
    }
说明:
1、runBat中执行db2cmd时需加上-c -w -i script 
2、dozip,ftpUp,delFile方法省略...
posted on 2007-01-18 21:28 sojust 阅读(3741) 评论(2)  编辑  收藏 所属分类: java

FeedBack:
# re: Runtime.getRuntime() .exec执行bat中db2cmd 时的问题
2013-09-05 15:52 | hy
遇到根楼主类似的问题,但我的是依次执行多个bat,貌似实现不了啊  回复  更多评论
  
# re: Runtime.getRuntime() .exec执行bat中db2cmd 时的问题
2013-09-05 17:38 | hy
//以下代码为控制台输出相关的批出理
String line = null ;
BufferedReader reader = new BufferedReader( new InputStreamReader(child.getInputStream()));
while ((line = reader.readLine()) != null )
{
System.out.println(line);
}
reader.close();
这一段的作用是什么  回复  更多评论
  

只有注册用户登录后才能发表评论。


网站导航:
 
    梦有多远,路就有多远......