Reputation: 190799
I have a eclipse plugin code to manipulate a class (smcho.Hello) in a project/workspace. I could create a CompilationUnit and did some modifications on it, but I need to save the result in different file to check the differences between the two version.
This is the code how I get the CompilationUnit.
IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();
IProject project = root.getProject("Hello");
project.open(null);
IJavaProject javaProject = JavaCore.create(project);
IType lwType = javaProject.findType("smcho.Hello");
org.eclipse.jdt.core.ICompilationUnit lwCompilationUnit = lwType.getCompilationUnit();
final ASTParser parser = ASTParser.newParser(AST.JLS3);
parser.setKind(ASTParser.K_COMPILATION_UNIT);
parser.setSource(lwCompilationUnit);
parser.setResolveBindings(true); // we need bindings later on
CompilationUnit unit = (CompilationUnit) parser.createAST(null /* IProgressMonitor */);
// modify the unit AST node
How can I save this modified unit into a new file?
Upvotes: 2
Views: 2298
Reputation: 3095
You can use an ASTRewriter
to do so.
// get the ast rewriter
final ASTRewrite rewriter = ASTRewrite.create(ast);
// get the current document source
final Document document = new Document(unit.getSource());
// compute the edits you have made to the compilation unit
final TextEdit edits = rewriter.rewriteAST();
// apply the edits to the document
edits.apply(document);
// get the new source
String newSource = document.get();
// now write this source to some other file.
Check the link below. This gives insight on how to write the AST changes to the file.
http://www.eclipse.org/articles/article.php?file=Article-JavaCodeManipulation_AST/index.html
Update: This is how i write to the file:
File file = new File(destFile);
FileUtils.writeStringToFile(File file, String newSource)
Upvotes: 5
Reputation: 190799
This is the code that I could use for saving the rewritten ast into another file. I wonder if there might be simpler way.
Document document = new Document(lwCompilationUnit.getSource());
rewrite.rewriteAST().apply(document);
String source = document.get();
String destFile = "...";
Helper.toFile(source, destFile);
public static void toFile(String source, String outputPath)
{
try{
// Create file
FileWriter fstream = new FileWriter(outputPath);
BufferedWriter out = new BufferedWriter(fstream);
out.write(source);
//Close the output stream
out.close();
}catch (Exception e){//Catch exception if any
System.err.println("Error: " + e.getMessage());
}
}
Upvotes: 1