简体   繁体   English

如何从注释处理器创建文件名中带有空格的资源

[英]How to create a resource with spaces in file name from Annotation Processor

When generating resource file on compile time using javax.annotation.processing.Processor , not able to create files with spaces in the file name.在编译时使用javax.annotation.processing.Processor生成资源文件时,无法创建文件名中带有空格的文件。

Simplified code to reproduce the problem:重现问题的简化代码:

public class SampleAnnotationProcessor extends AbstractProcessor {

@Override
public boolean process(Set<? extends TypeElement> annotations, RoundEnvironment env) {
    for (Element element : env.getElementsAnnotatedWith(SampleAnnotation.class)) {
        FileObject resource = processingEnv.getFiler()
                .createResource(StandardLocation.CLASS_OUTPUT, "configs.generated", "file name with spaces.xml", element);
        // ...
    }

    return true;
}

} }

On jdk1.8.0_212.jdk it fails with:jdk1.8.0_212.jdk它失败了:

java.lang.IllegalArgumentException: Invalid relative name: file name with spaces.xml

As such resource would be packaged just fine into jar if present in src/resources , I assume the same should be possible when auto-generated as well.由于如果存在于src/resources中,此类资源将被很好地打包到 jar 中,我认为在自动生成时也应该可以。

Is there a way to escape the spaces, or do something else to generate such files on compile time?有没有办法逃避空格,或者做其他事情来在编译时生成这样的文件?

As a brute force approach, renaming the resulting file does the trick:作为蛮力方法,重命名生成的文件可以解决问题:

String nameWithoutSpaces = desiredFilename.replace(" ", "-");
FileObject resource = processingEnv.getFiler()
                .createResource(StandardLocation.CLASS_OUTPUT, "configs.generated", nameWithoutSpaces, element);

Path generatedResourcePath = Paths.get(resource.toUri());
Path desiredPath = generatedResourcePath.getParent().resolve(desiredFilename);
Files.move(generatedResourcePath, desiredPath, StandardCopyOption.REPLACE_EXISTING);

Still looking for more conventional approach.仍在寻找更传统的方法。 Reference to a bug/ticket or specification note explaining why a resource can't have spaces work too.参考解释为什么资源不能有空间工作的错误/票证或规范说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM