这可能是一个错误,但是使用Elcipse 4.2.2中的JDK时,有必要创建ICompilationUnit的工作副本,以便将TextEdit应用于文件。
targetUnit.becomeWorkingCopy(new SubProgressMonitor(monitor, 1)); ... do work on the source file ... formatUnitSourceCode(targetUnit, new SubProgressMonitor(monitor, 1)); targetUnit.commitWorkingCopy(true, new SubProgressMonitor(monitor, 1));
格式化本身是这样完成的:
public static void formatUnitSourceCode(ICompilationUnit unit, IProgressMonitor monitor) throws JavaModelException { CodeFormatter formatter = ToolFactory.createCodeFormatter(null); ISourceRange range = unit.getSourceRange(); TextEdit formatEdit = formatter.format(CodeFormatter.K_COMPILATION_UNIT, unit.getSource(), range.getOffset(), range.getLength(), 0, null); if (formatEdit != null && formatEdit.hasChildren()) { unit.applyTextEdit(formatEdit, monitor); } else { monitor.done(); }}


