void (final PsiJavaFile javaFile, final PsiDirectory targetDir) { final PsiPackage aPackage = JavaDirectoryService.getInstance().getPackage(targetDir); if (aPackage == null) return; final PsiPackageStatement oldStatement = javaFile.getPackageStatement(); final Project project = javaFile.getProject(); if ((oldStatement != null && !oldStatement.getPackageName().equals(aPackage.getQualifiedName()) || (oldStatement == null && aPackage.getQualifiedName().length() > 0))) { CommandProcessor.getInstance().executeCommand(project, () -> { try { PsiElementFactory factory = JavaPsiFacade.getElementFactory(project); final PsiPackageStatement newStatement = factory.createPackageStatement(aPackage.getQualifiedName()); if (oldStatement != null) { oldStatement.replace(newStatement); } else { final PsiElement addedStatement = javaFile.addAfter(newStatement, null); final TextRange textRange = addedStatement.getTextRange(); // ensure line break is added after the statement CodeStyleManager.getInstance(project).reformatRange(javaFile, textRange.getStartOffset(), textRange.getEndOffset()+1); } } catch (IncorrectOperationException e) { // ignore } }, JavaBundle.message("command.name.updating.package.statement"), null); } }