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



我编写了这段代码来完成任务,但没有出现对话框。一旦我在代码中使用 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("nnSize = %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,如果可能的话,它将转换("适应"(选择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;
}

最新更新