1. 程式人生 > >java中調用kettle轉換文件

java中調用kettle轉換文件

post sso sna 命名 exce content tro 沒有 bsp

java中調用kettle轉換文件

通過命令行也能夠調用,然後java中調用命令行代碼也能夠。這樣沒有和java代碼邏輯無縫集成。本文說明kettle5.1中假設通過其它API和java代碼無縫集成;網上大多數資料都是低版本號的。在kettle5.x中已經不能執行。

1、 須要哪些jar文件

技術分享

以kettle開頭的是必須,上圖最以下三個也要;紅色框中的兩個是我測試轉換用到的。各自是生成UUID和文件。

要是少了jar文件,執行程序一定報錯。大家依據錯誤到kettle安裝文件夾LIB中找對應的jar加到編譯路徑中。

2、 演示樣例說明怎樣通過java調用轉換

演示樣例是把一個excel的內容導入到數據中。excel僅僅有兩列,所以須要在kettle中生成一列uuid,然後導入到數據庫中。

技術分享

默認生成的uuid有‘-’間隔符,所以通過“Replace in string”替換為空;

技術分享

excel步驟,使用了命名參數,所以要在轉換配置設置命名參數。

技術分享

演示樣例代碼例如以下:

publicclass KettleUtil2 {

   public String RES_DIR = "res";

   private String fullFileName ;

 

   public KettleUtil2(String fileName){

      fullFileName = System.getProperty("user.dir") + File.separator + RES_DIR;

      fullFileName += File.separator + fileName;

   }

   /**

    * 沒有參數是,設置參數為null

    * @param paras

    */

   publicvoid runTransformation(Map<String,String> paras) {

      try {

        KettleEnvironment.init();

 

        TransMeta transMeta = new TransMeta(fullFileName);

        Trans  transformation =new Trans(transMeta);

       

        for(Map.Entry<String, String> entry: paras.entrySet()) {

            transformation.setParameterValue(entry.getKey(), entry.getValue());

        }

 

        transformation.execute(null);

        transformation.waitUntilFinished();

       

        if (transformation.getErrors() > 0) {

           thrownew RuntimeException(

                 "There wereerrors during transformation execution.");

        }

      } catch (KettleException e) {

        System.out.println(e);

      }

   }

}


最後調用代碼例如以下:

publicclass EtlTest {

 

   publicstaticvoid main(String[] args) {

      KettleUtil2 etl = new KettleUtil2("testimport.ktr");

      Map<String,String> para = new HashMap<String,String>();

     

      //給轉換中命名參數賦值

      para.put("XlsName", "data");

      etl.runTransformation(para);

   }

}


java中調用kettle轉換文件