levik
levik

Reputation: 117499

Get the absolute path of the currently edited file in Eclipse

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?

Upvotes: 18

Views: 22491

Answers (6)

user3491194
user3491194

Reputation: 1

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();

Upvotes: -2

Chris Marasti-Georg
Chris Marasti-Georg

Reputation: 34650

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.

Upvotes: 22

ChrisJF
ChrisJF

Reputation: 7190

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);

Upvotes: 5

James E. Ervin
James E. Ervin

Reputation: 161

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.

Upvotes: 6

MikaLa
MikaLa

Reputation:

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

Upvotes: 0

Todd Wallentine
Todd Wallentine

Reputation:

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

file.getLocation().toOSString()

Upvotes: 1

Related Questions