2016-05-14 50 views
1

我想在我的注释处理器中从我的andoid studio项目访问资源。Android注释处理器访问资源(资产)

我第一次尝试从文件管理器使用的getResource方法:

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

,但它总是扔,只是返回 “的src/main/RES /布局/ 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()); 
      } 

,但它throwes一个空指针异常

+0

对传统Java(除了Android之外)工作的工具中的术语“资源”的任何引用都指的是Java/JAR资源,而不是Android资源。 – CommonsWare

+0

我找到了一个解决方案 – H3x0n

回答

5

我用下面的从我的注释处理器获得的布局文件夹:

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"); 
    }