Error while saving java file in IntelliJ.

I want to add code in Java file and save that file in background.
Below is the code that I am writing, But getting error "com.intellij.util.IncorrectOperationException: Must not change document outside command or undo-transparent action. See com.intellij.openapi.command.WriteCommandAction or com.intellij.openapi.command.CommandProcessor"

 
final String fieldSource = "public static final String abc = \"abc\";";
final String methodSource = "public static String getAbc() {return abc;}";
// add contents to class
PsiElementFactory elementFactory = PsiElementFactory.SERVICE.getInstance(project);
final PsiField newField = elementFactory.createFieldFromText(fieldSource, null);
final PsiMethod newMethod = elementFactory.createMethodFromText(methodSource, null);
  
ApplicationManager.getApplication().runWriteAction(new Runnable() {
 
     @Override
 
    public void run() {
        try {
            javaFile.add(newField);
            javaFile.add(newMethod);
            CodeStyleManager.getInstance(project).reformat(javaFile);
            FileDocumentManager fileDocumentManager = FileDocumentManager.getInstance();
            Document document = fileDocumentManager.getDocument(javaFile.getVirtualFile());
            if (document != null) {
                fileDocumentManager.saveDocument(document);
            }
        }catch (Exception e)
        {
            sourceRootsList.append("error"+e.toString()).append("\n");
        }

    }
});


Kindly help how I can save Java file after adding code

1 comment
Comment actions Permalink

The error message you've posted tells you exactly what you need to do to fix the problem. The exception is caused by the modifications and reformatting that you perform outside of a command, not by file saving.

(Note that there is most likely no need to either reformat the code or save the file. IntelliJ automatically formats added elements and saves files when necessary.)

0

Please sign in to leave a comment.