2014-09-05 75 views
0

编辑:我刚刚发现,不是IOExcpetion,但FilerException被抛出。因此,我在说明和标题中改变了这一点。Filer总是抛出FilerException

我正在使用Annotation Processing来为我的java项目生成一些文件。现在,当Annotation Processing尝试生成我的文件时,我总是得到一个FilerException

这是我创建文件的方式(GenClass和GenAnnotation是抽象生成的类的自定义类,它们在大约半年内没有改变,所以我确信这个错误不在某处。我写的文件,也没有在去年改变):

public static boolean generateJavaSourceFile(final ProcessingEnvironment processingEnv, 
     final GenClass element, final String fileName, final Class<?> generatorClass) { 
    boolean succeed = false; 
    Writer fw = null; 
    Filer f = processingEnv.getFiler(); 

    // Mark the class as generated 
    GenAnnotation generatedAnnotation = getAnnotation(generatorClass); 
    element.pushImport(generatedAnnotation); 
    element.addAnnotation(generatedAnnotation); 

    try { 
     JavaFileObject jfo = f.createSourceFile(fileName, (Element[]) null); 
     // create new java source file 
     fw = jfo.openWriter(); 
     // write the GenClass object into file 
     fw.write(element.toString()); 

     succeed = true; 
    } catch (FilerException e) { 
     LOGGER.severe("Couldn't generate file (" + fileName + ")!"); 
     processingEnv.getMessager().printMessage(Kind.ERROR, 
               "Could not create source file " + fileName 
                 + " because it already exists"); 
     throw new RuntimeException(e.getMessage(), e); 
    } catch (IOException e) { 
     LOGGER.severe("Couldn't generate file (" + fileName + ")!"); 
     throw new RuntimeException(e.getMessage(), e); 
    } finally { 
     if (fw != null) { 
      try { 
       fw.close(); // flush and close the stream 
      } catch (IOException e) { 
       LOGGER.severe("Couldn't close file [" + fileName + "]!"); 
      } 
     } 
    } 
    LOGGER.fine(fileName + " written"); 
    return succeed; 

这是异常的消息:

Source file already created: /path/to/the/file/to/create 

我没有改变我的处理器的东西,但只有错误发生在特定类型的文件中(我们使用Filters进行过滤数据),并且我没有更改生成过滤器的处理器上的任何内容。我添加了一个新的处理器,使用不同的注释并正确生成这些文件。

有谁知道这个错误的原因可能是什么?

+0

您是否使用不同的文件名来使用generateJavaSourceFile?异常消息表示“指定名称的文件已经创建,并且系统不能创建多个同名的文件”。我想你再使用一个文件名。 – 2014-09-05 08:53:24

+0

是的文件名是要写入的类的标准名称。 – mvieghofer 2014-09-05 08:54:47

+0

LOGGER.severe()记录什么?你如何得到这个异常消息“源文件已创建:/路径/到/文件/到/创建”?异常消息中执行代码时创建的文件名是否与文件名不同?如果它们不同,那么异常消息中的文件名是什么意思? – 2014-09-05 10:01:42

回答

0

我在另一个处理器(与生成过滤器的处理器无关)并且导致此错误时出错。现在我修复了这个错误也停止了这种行为。我不确定为什么这个FilerException总是发生,但它现在消失了。

相关问题