2016-05-14 51 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"); 
    }