问题
I want to access a resource from my andoid studio project in my annotation processor.
I first tried to use the getResource method from filer:
FileObject fo = processingEnv.getFiler().getResource(StandardLocation.SOURCE_PATH, "", "src/main/res/layout/activity_main.xml");
, but it always throwed a exception that just returned "src/main/res/layout/activity_main.xml" as a message.
Next think i have tried was
this.getClass().getResource("src/main/res/layout/activity_main.xml")
, but this always returned null.
The last think i have tried to use was this:
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());
}
, but it throwes a null pointer exception
回答1:
I used the following to get the layout folder from my annotation processor:
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");
}
回答2:
Processor instance runs at the root level of the project, so you can do it in an easy way like so:
String fileSeparator = System.getProperty("file.separator");
String absoluteFilePth = "app" + fileSeparator + "src" + fileSeparator + "main" + fileSeparator + "res" + fileSeparator + "layout";
File file = new File(absoluteFilePth);
Regards,
来源:https://stackoverflow.com/questions/37225786/android-annotation-processor-access-resources-assets