How to create/add resources

From Bioclipse
Jump to: navigation, search
Development tutorial
Responsible author:Ola
Bioclipse version:N/A
"N/A" is not a number.
Last updated:2009-10-10


The Bioclispe Explorer (or Bioclipse Navigator, we should decide on a name) has Projects, Folders, and Files which all implement the IResource interface. Project implements IProject, File implements IFile, and Folder implements IFolder. All interfaces hence extend IResource.

Creating resources

To create a resource, you first have to create a resource handle and then tell it to create the resource. The following snippet uses resource handles to create a project, a folder, and a file.

IWorkspace workspace = ResourcesPlugin.getWorkspace();
  IWorkspaceRoot root = workspace.getRoot();
  IProject project  = root.getProject("MyProject");
  IFolder folder = project.getFolder("Folder1");
  IFile file = folder.getFile("hello.txt");
  //at this point, no resources have been created
  if (!project.exists()) project.create(null);
  if (!project.isOpen());
  if (!folder.exists()) 
     folder.create(IResource.NONE, true, null);
  if (!file.exists()) {
     byte[] bytes = "File contents".getBytes();
     InputStream source = new ByteArrayInputStream(bytes);
     file.create(source, IResource.NONE, null);

To get the selected project/folder:

 ISelection sel=PlatformUI.getWorkbench().getActiveWorkbenchWindow().getSelectionService().getSelection();

Add the following method to extract the selected resource:

  IResource extractSelection(ISelection sel) {
     if (!(sel instanceof IStructuredSelection))
        return null;
     IStructuredSelection ss = (IStructuredSelection) sel;
     Object element = ss.getFirstElement();
     if (element instanceof IResource)
        return (IResource) element;
     if (!(element instanceof IAdaptable))
        return null;
     IAdaptable adaptable = (IAdaptable)element;
     Object adapter = adaptable.getAdapter(IResource.class);
     return (IResource) adapter;

See the following link for the whole story: