import groovy.xml.MarkupBuilder
//该文件用于生成本地xml配置文件
def toDimens(String filePath,String targetPath) {
def file = new File(targetPath)
if (file.exists())
file.delete()
def writer = file.newPrintWriter()
def xml = new MarkupBuilder(writer)
//生成xml文件
writer.append('<?xml version="1.0" encoding="utf-8"?> \n')
xml.resources {
new File(filePath).eachLine{line->
bits = line.tokenize("=")
try {
dimen(name:bits[0].trim(),bits[1].trim())
} catch (Exception e) {
//exceptions pah!
}
}
}
writer.flush()
//控制台输出文件信息
println writer.toString()
writer.close()
}
java调用groovy:
/**
* 生成xml文件 * * @param filePath * 源文件 * @param targetPath * 生成文件路径 * @param type * 生成配置文件的类型 */ public static void pro2xml(String filePath,String targetPath,int type) { // System.out.println("============生成xml文件==========="); ClassLoader parent = Utils.class.getClassLoader(); GroovyClassLoader loader = new GroovyClassLoader(parent); try { GroovyObject groovyObject = null; File tempFile = new File(Constants.GROOVY_PATH); // 加载类S Class<?> groovyClass = loader.parseClass(tempFile); groovyObject = (GroovyObject) groovyClass.newInstance(); System.out.println("-> " + groovyObject.getClass()); if (type == Constants.METHOD_TODIMENS) { groovyObject.invokeMethod("toDimens",new Object[] { filePath,targetPath }); } else if (type == Constants.METHOD_TOARRAY) { groovyObject.invokeMethod("toArray",targetPath }); } else { groovyObject.invokeMethod("toString",targetPath }); } // 执行 groovy方法,生成xml配置文件 GroovyShell gShell = new GroovyShell(parent); gShell.setVariable("filePath",filePath); gShell.setVariable("targetPath",targetPath); gShell.evaluate(tempFile); } catch (Exception e) { e.printStackTrace(); } finally { // 删除properties文件 // File file = new File(filePath); // if (file.exists()) { // file.delete(); // } } } 原文链接:https://www.f2er.com/xml/299780.html