How to write Java source code as a String to file in IntelliJ plugin

38 Views Asked by At

I'm writing an IntelliJ plugin that generate a unit test class based on a Java source file (for now only support Java).

I have to admit that I have no experience about Kotlin. All the code, I copied from some GitHub

    override fun actionPerformed(e: AnActionEvent) {
//        UtTestsDialogProcessor.createDialogAndGenerateTests(e.project, )
        val file = e.getData(CommonDataKeys.PSI_FILE) ?: return
        val editor = e.getRequiredData(CommonDataKeys.EDITOR)
        val selectedElement = getSelectedElement(editor, file) ?: return
        val srcModule = ModuleUtilCore.findModuleForPsiElement(selectedElement) ?: return

        val srcClass = getContainingClass(selectedElement)
        val srcDir: PsiDirectory = selectedElement.containingFile.containingDirectory
        val srcPackage = JavaDirectoryService.getInstance().getPackage(srcDir) ?: return

        val propertiesComponent = PropertiesComponent.getInstance()
        var testModule: Module = suggestModuleForTestsReflective(file.project, srcModule)
        val testRootUrls = computeTestRoots(
            testModule
        )

        //            final HashSet<VirtualFile> testFolders = new HashSet<VirtualFile>(); //from v14
//        checkForTestRoots(srcModule, testFolders); //from v14
        if (testRootUrls == null || testRootUrls.isEmpty() && computeSuitableTestRootUrls(testModule!!).isEmpty()) {
            testModule = srcModule
        }
        val targetDirectory: PsiDirectory? = TargetDirectoryLocator.getOrCreateDirectory(file.project, srcPackage, testModule)

        val testClassContent = "public class UnitTest {  @Test public void test() {…}}";
        //NOW I'M STUCK HERE. HOW TO WRITE THIS CONTENT TO A FILE IN targetDirectory?
    }

I search on Google but cannot find any example how to write the String to Java file (let say UnitTest.java). Please help, my time is running out.

Edit: I'm facing NO error. Just don't know how to write String to Java file. Please don't ask for log, or debug detail.

0

There are 0 best solutions below