在Java中,我试图使用eclipse在编辑器上以编程方式打开一个文件。对我来说,编辑器是IFileEditorInput的实例很重要。我使用了以下代码:
IPath path = new Path(filePath);
System.out.println("PATH:"+path);
IFile ifile=ResourcesPlugin.getWorkspace().getRoot().getFile(path);
System.out.println("IFILE: "+ifile);
//IFileEditorInput editorInput= new FileEditorInput(ifile);
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
try {
IDE.openEditor(page, ifile);
} catch (PartInitException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
稍后在某个时候,我需要访问该文件,特别是在编辑器类的 init(( 方法中,如下所示:
@Override //IEditor
public void init(IEditorSite site, IEditorInput input) throws PartInitException {
if (input instanceof IFileEditorInput) {
try {
setSite(site);
setInput(input);
IFile ifile=((IFileEditorInput)input).getFile();
File file=null;
if(ifile.getLocation()==null)
{
System.out.println("file location is NULL..exiting");
System.exit(0);
}
else
file = ifile.getLocation().toFile();
问题是 ifile.getLocation(( 总是返回 null,因此,我无法使用 File 类访问该文件。我做错了什么?谢谢。
编辑:我的程序的输出是:
PATH:D:/EbticDATA/Etisalat/Zaid/.EBTIC8/Service_Corridor.xml
IFILE: L/EbticDATA/Etisalat/Zaid/.EBTIC8/Service_Corridor.xml
file location is NULL..exiting
你给出的路径
ResourcesPlugin.getWorkspace().getRoot().getFile(path);
必须是相对于工作区中存在的文件的工作区根目录的路径。
您可以使用getFileForLocation
指定一个路径,该路径是完整的文件系统路径:
ResourcesPlugin.getWorkspace().getRoot().getFileForLocation(path);
但这仅在生成的文件位于工作区中时才有效。
通常,IFile
仅适用于工作区中的文件 - 但您可以创建指向工作区外部文件的"链接"。
如果要编辑不在工作区中的文件,请使用
public static IEditorPart openEditor(IWorkbenchPage page, URI uri,
String editorId, boolean activate)
IDE
传入要编辑的文件URI
和编辑器 ID 的方法。
在这种情况下,在编辑器中,IEditorInput
将是IURIEditorInput
的实例,而不是IFileEditorInput
。