【问题标题】:How to programatically open a file on Editor in eclipse?如何以编程方式在 Eclipse 中的编辑器上打开文件?
【发布时间】:2018-03-15 09:43:47
【问题描述】:

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

稍后,我需要访问该文件,具体在Editor类的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

【问题讨论】:

  • 文件是否已经存在于文件系统中,或者您是否在程序中创建了该文件但没有写入磁盘?也从这个docs我找不到方法ifile.getLocation()
  • filePath 的值是多少?它是相对于工作空间根目录的路径吗?
  • 文件系统中已经存在该文件。 filePath 的值是一个文件系统路径,类似于 D:/Project...

标签: java eclipse file eclipse-plugin editor


【解决方案1】:

你给的路径

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

【讨论】:

    猜你喜欢
    • 2013-11-18
    • 2017-06-09
    • 1970-01-01
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2015-04-09
    • 2012-09-19
    • 1970-01-01
    相关资源
    最近更新 更多