我正在使用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");
答案 0 :(得分:3)
既然你已经有了字符串表示,那么:
Files.write(new File("Modified.java").toPath(), cu.toString(), StandardCharsets.UTF_8);