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

时间:2018-01-19 21:42:18

标签: eclipse-plugin

我写了这段代码来完成任务,但是没有出现对话框。只要我在代码中使用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;
    }
}

2 个答案:

答案 0 :(得分:0)

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,如果可能,它会将选择转换('适应')IFile。这不需要ICompilationUnit,并且适用于使用文件的任何视图或编辑器。

答案 1 :(得分:0)

@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;
}