1

我正在使用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");
4

1 回答 1

5

既然你已经有了字符串表示,那么这个呢:

Files.write(new File("Modified.java").toPath(), cu.toString(), StandardCharsets.UTF_8);
于 2016-08-10T22:11:34.777 回答