How to get the Path of current selected file in Eclipse?
I want to get the path of current selected file in 开发者_如何学编程Eclipse workspace but my project is a simple view plug-in project.
I just want to display the name/path of the file selected as soon as user opens the view.
You get the current selection as mentioned by @Danail Nachev. See http://www.eclipse.org/articles/Article-WorkbenchSelections/article.html for information on working with the selection service.
Once you have the selection, the most common pattern is:
if (selection instanceof IStructuredSelection) {
IStructuredSelection ssel = (IStructuredSelection) selection;
Object obj = ssel.getFirstElement();
IFile file = (IFile) Platform.getAdapterManager().getAdapter(obj,
IFile.class);
if (file == null) {
if (obj instanceof IAdaptable) {
file = (IFile) ((IAdaptable) obj).getAdapter(IFile.class);
}
}
if (file != null) {
// do something
}
}
Edit:
Usually you get an InputStream
from the IFile
and process it that way. Using some FileSystemProviders or EFS implementations, there might not be a local path to the file.
PW
You can retrieve the current workbench selection using two methods with the following code:
- through the Workbench SelectionService
getViewSite().getSelectionProvider().getSelection()
getViewSite().getWorkbenchWindow().getSelectionService()
You can find more information in this article.
Using the global workbench selection is the better approach, because it enables your view to get selection from everywhere, which is something the user might expect (I at least do). Also, almost all of the views in Eclipse (and I don't know exceptions to this rule) are using this approach.
If you absolutely must to tie your view to another view, then you can get all IWorkbenchPage
iterate over them and search for the view by its ID and when you find the view, you call get its SelectionProvider
to get the selection.
Only by reading this explanation, makes my hair go straight up. Considering that there might be multiple instances of the same view, you can end up with a selection from a random view. I'm not sure whether the user will make sense of how things work, unless you have some clear rules, which exactly view you need. It is up to you.
`
精彩评论