Nerzid Nerzid - 1 year ago 130
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

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

Is there anything like
or am I missing something ?

The example I've used from the Wiki:

files_list = FilePicker.chooseAndGetJavaFiles();

if (files_list == null || files_list.isEmpty()) {
} 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{
new MethodChangerVisitor().visit(cu,null);


private static class MethodChangerVisitor extends VoidVisitorAdapter{

public void visit(MethodDeclaration n, Object arg) {
// change the name of the method to upper case

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

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



Here is the solution;
Add Below Line;

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

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

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


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

Answer Source

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

Files.write(new File("").toPath(), cu.toString(), StandardCharsets.UTF_8);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download