Eclipse中的Resource

IWorkspace/IWorkspaceRoot/IProject/IFolder/IFile/IResource/IPath/IScope/IContainer
IResourceChangeListener/IResourceChangeEvent/IResourceDeltaVisitor

//访问工作空间
IWorkspace workspace = ResourcesPlugin.getWorkspace();

//获得工作空间中的资源层次结构的顶部
IWorkspaceRoot myWorkspaceRoot = ResourcesPlugin.getWorkspace().getRoot();
//访问工作空间中的项目
IProject myProject = myWorkspaceRoot.getProject("MyProj");
if(myProject.exists() && !myProject.isOpen())
    myProoject.open(null);

//根据位于工作空间外部的文件的内容来创建文件资源
IFolder imagesFolder = myWebProject.getFolder("images");
if (imagesFolder.exists()) {
    // create a new file
    IFile newLogo = imagesFolder.getFile("newLogo.png");
    FileInputStream fileStream = new FileInputStream("c:/MyOtherData/newLogo.png");
    newLogo.create(fileStream, false, null);
    // create closes the file stream, so no worries.  
}

//从原始文件复制 newLogo 文件
IFolder newImagesFolder = myProject.getFolder("newimages");
newImagesFolder.create(false, true, null);
IPath renamedPath = newImagesFolder.getFullPath().append("renamedLogo.png");
newLogo.move(renamedPath, false, null);
IFile renamedLogo = newImagesFolder.getFile("renamedLogo.png");

资源路径名不是完整的文件系统路径,而是基于项目的位置(通常是工作空间目录),要获取资源的完整文件系统路径,必须使用 IResource.getLocationURI 来查询它的位置。
给定文件系统路径,如果要获取对应的资源对象,则可以使用 IWorkspaceRoot.findFilesForLocationURI 或 IWorkspaceRoot.findContainersForLocationURI。

//控制文件系统刷新
IResource.refreshLocal(int depth, IProgressMonitor monitor)

//获得表示项目级别首选项的节点
IScopeContext projectScope = new ProjectScope(MyProject);
Preferences projectNode = projectScope.node("com.example.myplugin");
if (projectNode != null) {
    value = node.getBoolean("MyPreference", "true");
    //do something with the value.
}
projectNode.flush();

//查询文件的字符集(仅应返回对该文件显式定义的字符集)
String charset = myFile.getCharset(false);

//查询文件的字符集(返回隐含的字符集)
String charset = myFile.getCharset(true);

//获取文件内容描述
IFile file = ...;
IContentDescription description = file.getDescription();

//确定给定位置对于创建链接的资源是有效的
IWorkspace.validateLinkLocation(IResource resource, IPath location)

禁用链接资源
· 项目性质否决
<extension
 id="myNature"
 name="My Nature"
 point="org.eclipse.core.resources.natures">
 <runtime>
  <run class="com.xyz.MyNature"/>
 </runtime>
 <options allowLinking="false"/>
</extension>
· 小组挂钩
如果定义自己的资源库实现,则可以利用 org.eclipse.core.resources.teamHook 扩展点来防止在共享资源库类型的项目中创建链接的资源。

//定义路径变量
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IPathVariableManager pathMan = workspace.getPathVariableManager();
String name = "TEMP";
IPath value = new Path("c:\\temp");
if (pathMan.validateName(name).isOK() && pathMan.validateValue(value).isOK()) {
   pathMan.setValue(name, value);
} else {
   //invalid name or value, throw an exception or warn user
}

//创建相对于已定义的路径变量的链接资源
IProject project = workspace.getProject("Project");//assume this exists
IFolder link = project.getFolder("Link");
IPath location = new Path("TEMP/folder");
if (workspace.validateLinkLocation(location).isOK()) {
   link.createLink(location, IResource.NONE, null);
} else {
   //invalid location, throw an exception or warn user
}

//至此
link.getFullPath() ==> "/Project/Link"
link.getLocation() ==> "c:\temp\folder"
link.getRawLocation() ==> "TEMP/folder"
link.isLinked() ==> "true"
 
IFile child = link.getFile("abc.txt");
child.create(...);
child.getFullPath() ==> "/Project/Link/abc.txt"
child.getLocation() ==> "c:\temp\folder\abc.txt"
child.getRawLocation() ==> "c:\temp\folder\abc.txt"
child.isLinked() ==> "false"

//创建标记
IMarker marker = file.createMarker(IMarker.TASK);

//创建具有全局作用域的标记
IMarker marker = IWorkspace.getRoot().createMarker(IMarker.TASK);

//删除标记
try {
    marker.delete();
} catch (CoreException e) {
    // Something went wrong
}

//成批删除标记
int depth = IResource.DEPTH_INFINITE;
try {
    //如果把IMarker.PROBLEM改成null,则删除所有标记
    resource.deleteMarkers(IMarker.PROBLEM, true, depth);
} catch (CoreException e) {
    // something went wrong
}

//使用平台常量来处理属性
IMarker marker = file.createMarker(IMarker.TASK);
if (marker.exists()) {
try {
    marker.setAttribute(IMarker.MESSAGE, "A sample marker message");
    marker.setAttribute(IMarker.PRIORITY, IMarker.PRIORITY_HIGH);
} catch (CoreException e) {
    // You need to handle the case where the marker no longer exists      }
}
  
//查询资源以获取其标记及其子代的标记
IMarker[] problems = null;
   int depth = IResource.DEPTH_INFINITE;
try {
   problems = resource.findMarkers(IMarker.PROBLEM, true, depth);
} catch (CoreException e) {
   // something went wrong
}

使用 org.eclipse.core.resources.markers 扩展点来声明自己的标记类型
<extension id="mymarker" point="org.eclipse.core.resources.markers" />
<extension id="myproblem" point="org.eclipse.core.resources.markers">
   <super type="org.eclipse.core.resources.problemmarker"/>
   <super type="com.example.markers.mymarker"/>
   <attribute name="myAttribute" />
   <persistent value="true" />
</extension>

//创建 com.example.markers.myproblem 标记类型的实例
public IMarker createMyMarker(IResource resource) {
   try {
      IMarker marker = resource.createMarker("com.example.markers.myproblem");
      marker.setAttribute("myAttribute", "MYVALUE");
      return marker;
   } catch (CoreException e) {
      // You need to handle the cases where attribute value is rejected
   }
}

//查询自己的标记类型(所有mymarkers和myproblems)
public IMarker[] findMyMarkers(IResource target) {
   String type = "com.example.markers.mymarker";
   IMarker[] markers = target.findMarkers(type, true, IResource.DEPTH_INFINITE);
}

//在工作空间可运行程序内的工作单元中批处理插件对工作空间进行的修改
IWorkspaceRunnable myRunnable =
        new IWorkspaceRunnable() {
  public void run(IProgressMonitor monitor) throws CoreException {
   //do the actual work in here
   ...
  }
}

//运行工作空间可运行程序
IWorkspace workspace = ResourcesPlugin.getWorkspace();
workspace.run(myRunnable, myProject, IWorkspace.AVOID_UPDATE, null);

//从工作空间本身获取资源规则工厂
IWorkspace workspace = ResourcesPlugin.getWorkspace();
IResourceRuleFactory ruleFactory = workspace.getRuleFactory();

//可运行程序将资源从一个位置移至另一个位置,可以包含适用于此操作的规则
ISchedulingRule movingRule = ruleFactory.moveResource(sourceResource, destinationResource);
workspace.run(myRunnable, movingRule, IWorkspace.AVOID_UPDATE, null);

//使用 MultiRule 来组合多条规则
ISchedulingRule movingRule = ruleFactory.moveResource(sourceResource, destinationResource);
ISchedulingRule modifyRule = ruleFactory.modifyResource(destinationResource);
workspace.run(myRunnable, MultiRule.combine(movingRule, modifyRule), IWorkspace.AVOID_UPDATE, null);

//不包括规则或更新标志的简短格式
workspace.run(myRunnable, null);

//指定工作空间根作为调度规则将锁定整个工作空间,直到可运行程序完成为止。
//这是执行工作空间更新的最稳当方法,但是它不太支持其他重视并行的插件。
workspace.run(myRunnable, workspace.getRoot(), IWorkspace.AVOID_UPDATE, null);

//跟踪插件运行时发生的所有工作空间更改
IResourceChangeListener listener = new MyResourceChangeReporter();
ResourcesPlugin.getWorkspace().addResourceChangeListener(listener, IResourceChangeEvent.POST_CHANGE);

//注册资源更改侦听器
IResourceChangeListener listener = new MyResourceChangeReporter();
ResourcesPlugin.getWorkspace().addResourceChangeListener(listener,
      IResourceChangeEvent.PRE_CLOSE | IResourceChangeEvent.PRE_DELETE
      | IResourceChangeEvent.PRE_AUTO_BUILD | IResourceChangeEvent.POST_AUTO_BUILD
      | IResourceChangeEvent.POST_CHANGE);

//实现资源更改侦听器
public class MyResourceChangeReporter implements IResourceChangeListener {
   public void resourceChanged(IResourceChangeEvent event) {
      IResource res = event.getResource();
      switch (event.getType()) {
         case IResourceChangeEvent.PRE_CLOSE:
            System.out.print("Project ");
            System.out.print(res.getFullPath());
            System.out.println(" is about to close.");
            break;
         case IResourceChangeEvent.PRE_DELETE:
            System.out.print("Project ");
            System.out.print(res.getFullPath());
            System.out.println(" is about to be deleted.");
            break;
         case IResourceChangeEvent.POST_CHANGE:
            System.out.println("Resources have changed.");
            event.getDelta().accept(new DeltaPrinter());
            break;
         case IResourceChangeEvent.PRE_AUTO_BUILD:
            System.out.println("Auto build about to run.");
            event.getDelta().accept(new DeltaPrinter());
            break;
         case IResourceChangeEvent.POST_AUTO_BUILD:
            System.out.println("Auto build complete.");
            event.getDelta().accept(new DeltaPrinter());
            break;
      }
   }
}

//查询资源变化的实现类
class DeltaPrinter implements IResourceDeltaVisitor {
   public boolean visit(IResourceDelta delta) {
      IResource res = delta.getResource();
      switch (delta.getKind()) {
         case IResourceDelta.ADDED:
            System.out.print("Resource ");
            System.out.print(res.getFullPath());
            System.out.println(" was added.");
            break;
         case IResourceDelta.REMOVED:
            System.out.print("Resource ");
            System.out.print(res.getFullPath());
            System.out.println(" was removed.");
            break;
         case IResourceDelta.CHANGED:
            System.out.print("Resource ");
            System.out.print(res.getFullPath());
            System.out.println(" has changed.");
            break;
      }
      return true; // visit the children
   }
}

//从提供的资源变化中获取进一步的信息
case IResourceDelta.CHANGED:
   System.out.print("Resource ");
   System.out.print(delta.getFullPath());
   System.out.println(" has changed.");
   int flags = delta.getFlags();
   if ((flags & IResourceDelta.CONTENT) != 0) {
         System.out.println("--> Content Change");
   }
   if ((flags & IResourceDelta.REPLACED) != 0) {
         System.out.println("--> Content Replaced");
   }
   if ((flags & IResourceDelta.MARKERS) != 0) {
         System.out.println("--> Marker Change");
         IMarkerDelta[] markers = delta.getMarkerDeltas();
         // if interested in markers, check these deltas
   }
   break;

//将工作移至 WorkspaceJob 子类型
class MyWorkspaceJob extends WorkspaceJob {
 public MyWorkspaceJob() {
  super("My Workspace Job");
 }
 public IStatus runInWorkspace(IProgressMonitor monitor) {
  //do the actual work in here
  doSomeWork();
  return Status.OK_STATUS;
 }
}

//对该作业附加调度规则以避免同时修改 myProject
MyWorkspaceJob job = new MyWorkspaceJob();
job.setRule(myProject);
job.schedule();

你可能感兴趣的:(Eclipse中的Resource)