doFinish() 方法
如下所示,doFinish() 方法将创建新文件并通过 IDE 中的编辑器打开新文件。将调用 openContentStream() 方法以获得给新文件填充内容的输入流。
清单 4. 初始的 doFinish() 方法 /** * The worker method. It will find the container, create the * file if missing or just replace its contents, and open * the editor on the newly created file. */ private void doFinish( String containerName, String fileName, IProgressMonitor monitor) throws CoreException { // create a sample file monitor.beginTask("Creating " + fileName, 2); IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot(); IResource resource = root.findMember(new Path(containerName)); if (!resource.exists() || !(resource instanceof IContainer)) { throwCoreException("Container "" + containerName + "" does not exist."); } IContainer container = (IContainer) resource; final IFile file = container.getFile(new Path(fileName)); try { InputStream stream = openContentStream(); if (file.exists()) { file.setContents(stream, true, true, monitor); } else { file.create(stream, true, monitor); } stream.close(); } catch (IOException e) { } monitor.worked(1); monitor.setTaskName("Opening file for editing..."); getShell().getDisplay().asyncExec(new Runnable() { public void run() { IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage(); try { IDE.openEditor(page, file, true); } catch (PartInitException e) { } } }); monitor.worked(1); }
openContentStream() 方法
如下所示,openContentStream() 方法将返回包含生成的静态字符串作为模板一部分的 ByteArrayInputStream。对于本文,字符串将被替换为模板文件的内容。
此方法中的代码是首先必须更改的,这样才能在创建时允许把更多有用的内容添加到新文件中。
清单 5. openContentStream() 方法 /** * Initialize file contents with a sample text. */ private InputStream openContentStream() { String contents = "This is the initial file contents for *.html " + "file that should be word-sorted in the Preview " + "page of the multi-page editor"; return new ByteArrayInputStream(contents.getBytes()); }
添加基本内容
新文件的内容不使用静态字符串值,您可以使用 getResourceAsStream() 方法把文件的内容载入到 InputStream 中,并且 doFinish() 方法可以用它来填充新文件。请做出如下所示的修改。
清单 6. 从资源获得输入流 /** * Initialize the file contents to contents of the * given resource. */ private InputStream openContentStream() { return this.getClass() .getResourceAsStream("templates/index-xhtml-template.resource"); }
index-xhtml-template.resource 文件中是有效的可扩展超文本标记语言(Extensible Hypertext Markup Language,XHTML)V1.0 Strict Web 页面。它有针对一组模拟企业样式表和 JavaScript 文件的一些基本标记和点。该文件列于清单 7 中。此文件与 NewXHTMLFileWizard 类在同一个包中,因此在本文中此文件位于 com.example.eclipse.wizards 包中。如果需要将文件放在其他包中,则可以像访问目录内的文件一样访问它(即,com.example.resources 是 /com/example/resources)。
(编辑:aniston)
|