我正在使用JavaParser并跟踪它的Wiki。问题是,即使我更改了方法的名称并向其添加了一个参数,该文件也不会更新。换句话说,更改不会保存。当我System.out.println更改的CompilationUnit时,它会用更改打印它,但是这些更改根本不影响源文件。
有什么像CompilationUnit.update()这样的东西吗?还是我遗漏了什么?
我从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);
}
}编辑:这里是解决方案,添加到下面一行;
Files.write(new File("Modified.java").toPath(), cu.toString(), StandardCharsets.UTF_8);更改行下的特殊字符(例如"ş,ü.“)
cu = JavaParser.parse(files_list.get(0));至
cu = JavaParser.parse(files_list.get(0),"UTF-8");发布于 2016-08-10 22:11:34
既然您已经有了字符串表示形式,那么下面这个呢:
Files.write(new File("Modified.java").toPath(), cu.toString(), StandardCharsets.UTF_8);https://stackoverflow.com/questions/38881876
复制相似问题