Java 如何在eclipse中以编程方式在编辑器上打开文件?
在Java中,我尝试使用eclipse以编程方式在编辑器上打开一个文件。编辑器是IFileEdit或Input的实例,这一点对我很重要。我使用了以下代码:Java 如何在eclipse中以编程方式在编辑器上打开文件?,java,eclipse,file,eclipse-plugin,editor,Java,Eclipse,File,Eclipse Plugin,Editor,在Java中,我尝试使用eclipse以编程方式在编辑器上打开一个文件。编辑器是IFileEdit或Input的实例,这一点对我很重要。我使用了以下代码: IPath path = new Path(filePath); System.out.println("PATH:"+path); IFile ifile=ResourcesPlugin.getWorkspace().getRoot().getFile(path);
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
文件是否已经存在于文件系统中,或者您是否在程序中创建了该文件但没有写入磁盘?同样,从这里我找不到方法ifile.getLocation()
文件路径的值是多少?它是相对于工作区根目录的路径吗?文件系统中已存在该文件。filePath的值是一个文件系统路径,类似于D:/Project。。。