2008-11-18 125 views
14

我想编写一个插件,在Eclipse中对当前编辑文件执行某些操作。但我不确定如何正确获取文件的完整路径。在Eclipse中获取当前编辑文件的绝对路径

这就是我现在做的事:

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

现在我有一个的IFile对象,我可以取回它的路径:

file.getFullPath().toOSString(); 

然而,这仍然只是相对路径的给我的工作区。我怎样才能从中获得绝对的路径?

回答

20

看起来你想要IResource.getRawLocation()。如果您想要双倍确定您拥有绝对路径,则返回IPath,其中也包含makeAbsolute()方法。

+0

IResource.getRawLocation()的链接现已更改。 – 2013-11-13 13:00:32

1

我通常会调用IFile.getLocation(),它返回一个IPath,然后调用IPath.toOSString()。

file.getLocation().toOSString() 
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 
5

我觉得更多的Java友好的解决方案是做使用以下命令:

IResource.getLocation().toFile() 

这需要的IPATH API(定义的getLocation()的一部分)的优势,将返回java.io.File实例。当然其他答案可能会让你到你想要的地方。

作为切入点,我发现IDE类(org.eclipse.ui.ide.IDE)是编辑器的一个有用的实用程序资源。

4

为我工作(!我测试了它)的答案是:

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

对于我来说,这个运行正常。

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

File file = workSpaceRoot.getRawLocation()。makeAbsolute()。toFile();从这个位置

文件列表:

文件[]文件= file.listFiles();