This is what I tried, but it failed.And it alerted that 'org.eclipse .core .internal.File cannot be cast to org.eclipse.core.resource.IProject'.

public void runDefaultAction(IStructuredSelection selection) {
    Object element = selection.getFirstElement();
    if (element instanceof IFile) {
        openFileAction.selectionChanged(selection);
        openFileAction.run();
        String selectedPathString = ((IFile) element).getFullPath().toString();
        System.out.println(selectedPathString);
        //get project absolute path
        ISelectionService service = navigator.getSite().getWorkbenchWindow()
                .getSelectionService();
        IStructuredSelection selection1 = (IStructuredSelection) service
                .getSelection("BIT_DEC.myNavigator");
        IProject iproject = (IProject) selection1.getFirstElement();
        String real_file_path = iproject.getLocation().toString();
        System.out.println(real_file_path);
        .....
有帮助吗?

解决方案

it alerted that 'org.eclipse .core .internal.File cannot be cast to org.eclipse.core.resource.IProject'.

Because:

enter image description here

Corrected last 3 lines of your code.

if(selection1.getFirstElement() instanceof IFile) {
  IFile file = (IFile) selection1.getFirstElement();
  String real_file_path = file.getLocation().toString();
  System.out.println(real_file_path);
}

其他提示

IFile has a getLocation() method that gives you the full path directly.

Note: The selection returned by the selection service will generally be the same as the selection you are given. You can get the project from an IFile by calling its getProject() method.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top