2016-08-05 3 views
0

У меня есть шаблон как org.eclipse.jface.text.templates.Template:плагин Затмения - Programatically создать файл из шаблона

Template template = new Template(name, description, contextTypeId, pattern, true); 

или лучше org.eclipse.cdt.core.model.Template:

Template template = new Template(templateString); 

Или, скажем, что шаблон уже находится в Preferences -> C/C++ -> Code Style -> Шаблоны кода, и я могу получить его прямо оттуда.

Теперь я хочу, чтобы создать файл из него, как, как вы делаете в мастере, но программно:

IFile mainTestFile = testFolder.getFile(resource.getName() + ".myfile"); 
    if (!mainTestFile.exists()) { 
     mainTestFile.create(template, true, null); 
    } 

К сожалению, это работает только для InputStream не для шаблона.

Как я могу программно создать файл в проекте eclipse из шаблона, который у меня есть?

+1

Какой класс 'Шаблон' это? –

+0

org.eclipse.jface.text.templates.Template; –

+0

О каком волшебнике вы говорите? Для использования шаблона обычно требуется «TemplateContext» и «TemplateContextType». –

ответ

0

Ok так, как я сделал это может показаться немного счетчик интуитивно, но это сработало:

Сначала вам нужен класс, который расширяет CDT NewSourceFileCreationWizardPage. Затем перегрузите метод createFile, чтобы использовать org.eclipse.jface.text.templates.Template, который вы сами определяете. Код шаблона будет сотречен в строке, которая может быть получена из файла ресурсов.

 Template myTemplate = new Template("My Template", "My Template for file", "com.my.template.contenttype.contenttype_context", templateString, true); 

     MyNewFileWizardPage myTemplateWizard = new MyNewFileWizardPage(); 

     mainTestFile = myTemplateWizard.createMyFile(myTemplate, mainTestFile.getLocation(), null); 

И обычай новый мастер-файл страницы:

class MyNewFileWizardPage extends NewSourceFileCreationWizardPage{ 

    private ITranslationUnit fNewFileTU = null; 

    @SuppressWarnings("restriction") 
    public IFile createMyFile(Template template, IPath filePath, IProgressMonitor monitor) throws CoreException { 
    if (filePath != null) { 
     if (monitor == null) 
      monitor = new NullProgressMonitor(); 
     try { 
      fNewFileTU = null; 
      IFile newFile = NewSourceFileGenerator.createSourceFile(filePath, true, monitor); 
      if (newFile != null) { 
       fNewFileTU = (ITranslationUnit) CoreModel.getDefault().create(newFile); 
       if (fNewFileTU != null) { 
        String lineDelimiter = StubUtility.getLineDelimiterUsed(fNewFileTU); 
        String content = CodeGeneration.getBodyFileContent(template, fNewFileTU, null, null, lineDelimiter); 
        if (content != null) { 
         fNewFileTU.getBuffer().setContents(content.toCharArray()); 
         fNewFileTU.save(monitor, true); 
         return newFile; 
        } 
       } 
      } 
     } finally { 
      monitor.done(); 
     } 
    } 
    return null; 
    } 
} 

Затем с созданным IFile вы можете изменить его в дальнейшем, если вы хотите что-нибудь изменилось в нем.