Nerzid Nerzid - 3 months ago 44
Java Question

JavaParser doesn't update source file

I'm using JavaParser and following its Wiki. Problem is even though I change the method's name and add a parameter to it, the file doesn't update. In other words, changes are not saved. When I

System.out.println
the changed
CompilationUnit
, it prints it with changes, but those changes don't affect the source file at all.

Is there anything like
CompilationUnit.update()
or am I missing something ?

The example I've used from the Wiki:

files_list = FilePicker.chooseAndGetJavaFiles();

if (files_list == null || files_list.isEmpty()) {
Errors.showError(Errors.COMMENT_GENERATOR_FILELIST_NULL_OR_EMPTY);
} else {

CompilationUnit cu = null;
FileInputStream in = new FileInputStream(files_list.get(0));
try {
cu = JavaParser.parse(in);
} catch (ParseException ex) {
Logger.getLogger(CommentGenerator.class.getName()).log(Level.SEVERE, null, ex);
} finally{
in.close();
}
new MethodChangerVisitor().visit(cu,null);

System.out.println(cu.toString());
}
}

private static class MethodChangerVisitor extends VoidVisitorAdapter{

@Override
public void visit(MethodDeclaration n, Object arg) {
// change the name of the method to upper case
n.setName(n.getName().toUpperCase());

// create the new parameter
Parameter newArg = ASTHelper.createParameter(ASTHelper.INT_TYPE, "value");

// add the parameter to the method
ASTHelper.addParameter(n, newArg);

}


}


EDIT:
Here is the solution;
Add Below Line;

Files.write(new File("Modified.java").toPath(), cu.toString(), StandardCharsets.UTF_8);





Change Below Line to use Special Characters as well(e.g "ş,ö,ü ...)

cu = JavaParser.parse(files_list.get(0));


To

cu = JavaParser.parse(files_list.get(0),"UTF-8");

Answer

Since you already have the string representation, what about this:

Files.write(new File("Modified.java").toPath(), cu.toString(), StandardCharsets.UTF_8);