Get the absolute path of the currently edited file in Eclipse
Asked Answered
K

6

17

I'd like to write a plugin that does something with the currently edited file in Eclipse. But I'm not sure how to properly get the file's full path.

This is what I do now:

IFile file = (IFile) window.getActivePage().getActiveEditor.getEditorInput().
    getAdapter(IFile.class);

Now I have an IFile object, and I can retrieve it's path:

file.getFullPath().toOSString();

However this still only gives me the path relative to the workspace. How can I get the absolute path from that?

Karafuto answered 18/11, 2008 at 18:12 Comment(0)
B
22

Looks like you want IResource.getRawLocation(). That returns an IPath, which also has a makeAbsolute() method if you want to be doubly sure you've got an absolute path.

Bandoleer answered 18/11, 2008 at 18:15 Comment(1)
The link from IResource.getRawLocation() has been changed now.Hyperbola
J
6

I think a more Java friendly solution would be to do use the following:

IResource.getLocation().toFile()

This takes advantage of the IPath API (the getLocation() part) and will return a java.io.File instance. Of course the other answers will probably get you to where you want to be too.

On a tangential note, I find the IDE class (org.eclipse.ui.ide.IDE) a useful utility resource when it comes to editors.

Jillene answered 2/9, 2009 at 23:50 Comment(0)
C
5

The answer that worked for me (and I tested it!) was:

// Get the currently selected file from the editor
IWorkbenchPart workbenchPart = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActivePart(); 
IFile file = (IFile) workbenchPart.getSite().getPage().getActiveEditor().getEditorInput().getAdapter(IFile.class);
if (file == null) throw new FileNotFoundException();
String path = file.getRawLocation().toOSString();
System.out.println("path: " + path);
Cowlick answered 15/2, 2012 at 19:8 Comment(0)
R
1

I usually call IFile.getLocation() which returns an IPath and then call IPath.toOSString().

file.getLocation().toOSString()
Roeder answered 19/11, 2008 at 17:23 Comment(0)
H
0
IWorkspace ws      = ResourcesPlugin.getWorkspace();  
IProject   project = ws.getRoot().getProject("*project_name*");

IPath location = new Path(editor.getTitleToolTip());  
IFile file     = project.getFile(location.lastSegment());

into file.getLocationURI() it's the absolute path
Holliman answered 8/12, 2008 at 14:22 Comment(0)
T
-2

For me, this run ok.

IWorkspaceRoot workSpaceRoot = ResourcesPlugin.getWorkspace().getRoot();

File file = workSpaceRoot.getRawLocation().makeAbsolute().toFile();

file list from this location:

File[] files = file.listFiles();

Tyika answered 2/4, 2014 at 20:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.