使用FreeMarker加载远程主机上模板文件,比如FTP,Hadoop等(转载)

都知道FreeMarker加载模板文件有以下三种方式:

1、从文件目录加载

2、从类路径加载

3、从Servlet上下文加载

其中第二个和第三个常用在Web开发环境中,类路径也会使用在普通的Java Project中,不限制开发环境。

本文主要说明如果模板文件不是和应用程序放在同一台主机上,那么如何去读取和解析这些模板文件呢?答案是可以解决的,FreeMarker就提供给

我们一种加载模板的方式,查看API就有URLTemplateLoader类,该类为抽象类,从名字就可以看出从给定的URL加载模板文件,这个URL并没有限定来源,

说明可以是其他各个地方的来源:FTP服务器,Hadoop,db等等。那么可以自定义个加载器,从这个类继承,实现里面的getUrl方法即可:

[java] view plaincopy在CODE上查看代码片派生到我的代码片
 
  1. /** 
  2.  *  
  3.  */  
  4. package com.XX.XX.freemarker;  
  5.   
  6. import java.net.MalformedURLException;  
  7. import java.net.URL;  
  8.   
  9. import freemarker.cache.URLTemplateLoader;  
  10.   
  11. /** 
  12.  * 自定义远程模板加载器,用来加载远程机器上存放的模板文件,比如FTP,Handoop等上的模板文件 
  13.  * @author Administrator 
  14.  * 
  15.  */  
  16. public class RemoteTemplateLoader extends URLTemplateLoader  
  17. {  
  18.     //远程模板文件的存储路径(目录)  
  19.     private String remotePath;  
  20.       
  21.     public RemoteTemplateLoader (String remotePath)  
  22.     {  
  23.         if (remotePath == null)  
  24.         {  
  25.           throw new IllegalArgumentException("remotePath is null");  
  26.         }  
  27.         this.remotePath = canonicalizePrefix(remotePath);  
  28.         if (this.remotePath.indexOf('/') == 0)  
  29.         {  
  30.             this.remotePath = this.remotePath.substring(this.remotePath.indexOf('/') + 1);  
  31.         }  
  32.     }  
  33.       
  34.     @Override  
  35.     protected URL getURL(String name)   
  36.     {  
  37.         String fullPath = this.remotePath + name;  
  38.         if ((this.remotePath.equals("/")) && (!isSchemeless(fullPath)))   
  39.         {  
  40.             return null;  
  41.         }  
  42.         if (this.remotePath.indexOf("streamFile") == -1 && this.remotePath.indexOf("webhdfs") != -1)//这个是针对不直接使用文件流形式进行访问和读取文件而使用的格式  
  43.         {  
  44.             fullPath = fullPath + "?op=OPEN";  
  45.         }  
  46.         URL url = null;  
  47.         try   
  48.         {   
  49.             url = new URL(fullPath);  
  50.         }   
  51.         catch (MalformedURLException e)   
  52.         {  
  53.             e.printStackTrace();  
  54.         }  
  55.         return url;  
  56.     }  
  57.   
  58.       
  59.     private static boolean isSchemeless(String fullPath) {  
  60.             int i = 0;  
  61.             int ln = fullPath.length();  
  62.   
  63.             if ((i < ln) && (fullPath.charAt(i) == '/')) i++;  
  64.   
  65.             while (i < ln) {  
  66.               char c = fullPath.charAt(i);  
  67.               if (c == '/') return true;  
  68.               if (c == ':') return false;  
  69.               i++;  
  70.             }  
  71.             return true;  
  72.           }  
  73. }  
原文地址:https://www.cnblogs.com/scwanglijun/p/4010945.html