此处为啥一直报找不到文件的异常:java.io.FileNotFoundException: Template "contextxml.ftl" not found.

public class ExportToXmlUtil {

private Configuration configuration = null;

public ExportToXmlUtil(){
    configuration = new Configuration();

// configuration.setDefaultEncoding("UTF-8");
}
public static void main(String[] args) {
ExportToXmlUtil test = new ExportToXmlUtil();
test.createContextXml();
}

public void createContextXml(){
    Map<String,String> dataMap=new HashMap<>();
    getData(dataMap);
    configuration.setClassForTemplateLoading(this.getClass(), "classpath:/template");  //FTL文件所存在的位置,放在与java相同的包下

    Template t=null;
    try {
        t = configuration.getTemplate("contextxml.ftl"); //文件名
    } catch (IOException e) {
        e.printStackTrace();
    }
    File outFile = new File("D:/forK8sOutFile/context.xml");  //生成文件的路径
    Writer out = null;
    try {
        out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile)));
    } catch (FileNotFoundException e1) {
        e1.printStackTrace();
    }

    try {
        t.process(dataMap, out);
    } catch (TemplateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}
//这里赋值的时候需要注意,xml中需要的数据你必须提供给它,不然会报找不到某元素错的.
private Map<String,String> getData(Map<String, String> dataMap) {
    dataMap.put("name", "testName");
    dataMap.put("auth", "testAuth");
    return dataMap;
}

}

我的项目结构图随后附上

resources下的template是否有contextxml.ftl文件呢

看是不是类拟问题,用以下方法试一下:


    public String readResources ( String pFilepath ) {
        byte[] tmpBYTE;
        String tmpCONTENT = "";
        StringBuffer tmpStringBuffer = new StringBuffer ( );

        try {
            ClassPathResource tmpFile = new ClassPathResource(pFilepath);
            InputStream tmpInputStreamReader = tmpFile.getInputStream();
            tmpBYTE = IOUtils.toByteArray(tmpInputStreamReader);
            tmpInputStreamReader.read(tmpBYTE);
            tmpCONTENT=new String(tmpBYTE);
            tmpInputStreamReader.close ( );

        } catch (IOException e) {
            e.printStackTrace();
        }

        return tmpCONTENT;
    }

路径中的/是不是需要转义下呢