用于在包资源管理器中检索活动文件长度的 Eclipse 插件

Eclipse Plugin to retrieve active file length in package explorer

我写了这段代码来完成任务,但是没有出现对话框。只要我在代码中使用 IFile 或 IResource,对话框就不会出现。

package com.example.helloworld.handlers;
public class SampleHandler extends AbstractHandler {

    @Override
    public Object execute(ExecutionEvent event) throws ExecutionException {
       IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event); 
       IWorkbench wb = PlatformUI.getWorkbench();
       IWorkbenchWindow activeWorkbenchWindow = wb.getActiveWorkbenchWindow();
       ISelectionService selectionService = activeWorkbenchWindow.getSelectionService();
       ISelection selection = selectionService.getSelection();
       IStructuredSelection structSelection = (IStructuredSelection) selection;
       IFile ir = ((IFile)((ICompilationUnit)structSelection.getFirstElement()).getResource());
       test = (String) ir.getName();
       MessageDialog.openInformation( window.getShell(),"File Size",String.format("\n\nSize = %s",test));
        return null;
    }
}

现代版本的 Eclipse 有更多的辅助方法,因此您可以通过更简单的方式获取文件:

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException
{
  IStructuredSelection selection = HandlerUtil.getCurrentStructuredSelection(event);

  if (!selection.isEmpty()) {
    IFile file = Adapters.adapt(selection.getFirstElement(), IFile.class);

    if (file != null {
      String name = file.getName();

      MessageDialog.openInformation(HandlerUtil.getActiveShell(event), "File Name",
                                    String.format("Name %s", name));
    }
  }

这是使用 HandlerUtil.getCurrentStructuredSelection 来处理从任何视图或编辑器获取当前结构化选择。

然后它使用 Adapters.adapt,如果可能的话,它会将 ('adapt') 选择转换为 IFile。这不需要 ICompilationUnit,并且适用于任何使用文件的视图或编辑器。

@Override
public Object execute(final ExecutionEvent event) throws ExecutionException {

    IStructuredSelection selection = HandlerUtil.getCurrentStructuredSelection(event);
    String test;
    Long size;
 if (!selection.isEmpty()) {
      IFile file = ((IFile)((ICompilationUnit)selection.getFirstElement()).getResource());
     if (file != null) {
       File realfile = file.getRawLocation().makeAbsolute().toFile();
       size = realfile.length();
       MessageDialog.openInformation(HandlerUtil.getActiveShell(event), "File Name",String.format(" %s", size));
      }
 } 
    return null;
}