Wednesday, October 31, 2012

Writing file from CompilationUnit (ASTNode)

When you have an object of iCompilationUnit, you can save it to the file.
  1. You need to create Document object from ICompilationUnit
  2. You need a ASTRewrite object from CompilationUnit
  3. Filling in the Document object using apply() method
  4. Storing the source code string from document.get() method
Document document = new Document(iCompilationUnit.getSource());
ASTRewrite rewriter = ASTRewrite.create(compilationUnit); // ? check if the parameter object type is correct

String source = document.get();

File file = new File(DEST_FILE_PATH);
FileUtils.writeStringToFile(file, source) 


You need to save apache file utilities to use the FileUtils.


1 comment:

  1. After a long search for a simple example of writing a Compilation unit to File that works, I found this one.

    Most of the example on AST you find on google are useless.
    Very nice Thank You