1

我想在生成文件之前测试文件是否不存在。

是否可以使用类似 isFileExist 的东西?

[template public generate(conf : Configuration) ? (isFileExist('/path/to/file.txt'))]
[file ('/path/to/file.txt', false, 'UTF-8')]
file content
[/file]
[/template]

提前致谢。

4

1 回答 1

1

我刚刚遇到了和你一样的问题,我终于通过在外部 Java 类中“外部化”这个函数来让它工作。这样,您只需定义一个方法,例如:

public boolean existsFile(String filepath) {
    Path p = Paths.get(filepath);
    p.normalize();
    File f = new File(filepath);
    return f.exists();
}

然后通过定义如下查询从 Acceleo 调用它:

[query public existsFile(filePath : String): 
    Boolean = invoke('utils.AcceleoUtils', 'existsFile(java.lang.String)', Sequence{filePath})
/]

这样,在您的示例中,您可以这样做

[template public generate(conf : Configuration)]
    [if existsFile('/path/to/file.txt')/]
        [file ('/path/to/file.txt', false, 'UTF-8')]
            file content
        [/file]
    [/if]

[/template]

pd:注意路径,因为“file”标签默认将文件输出到目标路径中,所以如果您没有提供绝对路径,则需要在调用时或在 existsFile 函数中包含它。

于 2014-09-15T09:51:25.233 回答