Android Annotation处理器访问资源(资产)

问题描述 投票:1回答:2

我想从我的注释处理器中的android studio项目访问资源。

我首先尝试使用filer中的getResource方法:

FileObject fo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, "", "src/main/res/layout/activity_main.xml");

,但它总是抛出一个异常,只是将“src / main / res / layout / activity_main.xml”作为消息返回。

接下来我想我试过了

this.getClass().getResource("src/main/res/layout/activity_main.xml")

,但这总是返回null。

我试图使用的最后一件事是:

JavaCompiler compiler = ToolProvider.getSystemJavaCompiler();
            StandardJavaFileManager fm = compiler.getStandardFileManager(null, null, null);
            Iterable<? extends File> locations = fm.getLocation(StandardLocation.SOURCE_PATH);
            for (File file : locations) {
                System.out.print(file.getAbsolutePath());
            }

,但它抛出一个空指针异常

java android android-resources annotation-processing
2个回答
6
投票

我使用以下方法从我的注释处理器获取布局文件夹:

private File findLayouts() throws Exception {
        Filer filer = processingEnv.getFiler();

        JavaFileObject dummySourceFile = filer.createSourceFile("dummy" + System.currentTimeMillis());
        String dummySourceFilePath = dummySourceFile.toUri().toString();

        if (dummySourceFilePath.startsWith("file:")) {
            if (!dummySourceFilePath.startsWith("file://")) {
                dummySourceFilePath = "file://" + dummySourceFilePath.substring("file:".length());
            }
        } else {
            dummySourceFilePath = "file://" + dummySourceFilePath;
        }

        URI cleanURI = new URI(dummySourceFilePath);

        File dummyFile = new File(cleanURI);

        File projectRoot = dummyFile.getParentFile().getParentFile().getParentFile().getParentFile().getParentFile().getParentFile();

        return new File(projectRoot.getAbsolutePath() + "/src/main/res/layout");
    }

1
投票

处理器实例在项目的根级别运行,因此您可以通过以下方式轻松完成:

String fileSeparator = System.getProperty("file.separator");
    String absoluteFilePth = "app" + fileSeparator + "src" + fileSeparator + "main" + fileSeparator + "res" + fileSeparator + "layout";
    File file = new File(absoluteFilePth);

问候,

© www.soinside.com 2019 - 2024. All rights reserved.