【问题标题】:Get the workspace root获取工作区根
【发布时间】:2017-10-20 09:03:32
【问题描述】:

我正在开发一个 Eclipse 插件,我正在尝试获取工作区根目录,以便稍后从工作区访问文件并从中读取内容。

我跳过了较短代码的错误处理

IProject project = file.getProject(); // file is the file open in editor
IFolder specificFolder = project.getFolder("test");
IFile fileFromSpecFolder = specificFolder.getFile("test.txt");
Path path = Paths.get(fileFromSpecFolder.getLocationURI());
BufferedReader reader = createReaderFor(path);
// later on read something from the file...

问题在于实现的getProject方法returns itself for projects or null for the project root

public IProject getProject() {
    return workspace.getRoot().getProject(path.segment(0));
}

path.segment(0)) 包含工作区根

我在这里把事情复杂化了吗?我怎样才能以另一种方式实现这一目标?

【问题讨论】:

  • @VeselinDavidov 我看到了这个问题,但不知道这是否正是我的情况
  • 对不起,我真的不明白你在问什么。
  • @greg-449 我想从工作区获取文件的路径。该文件位于固定位置:%workspaceroot%/test/test.txt

标签: java eclipse eclipse-plugin


【解决方案1】:

您可以使用 IFile 获取工作区中的路径:

IWorkspaceRoot root = ResourcesPlugin.getWorkspace().getRoot();

IPath path = new Path("project/folder/file");

IFile file = root.getFileForLocation(path);

要读取工作区中文件的内容,您应该使用IFile.getContents

InputStream is = file.getContents();

使用IFile.getCharset获取文本文件的字符集:

String charset = file.getCharset();

所以文件的Reader 将是:

Reader reader = new InputStreamReader(is, charset);

注意Pathorg.eclipse.core.runtime.Path

【讨论】:

  • 我应该使用Path path而不是IPath path吗?类型 Path 无法实例化。
  • 你有错误的Path 类导入 - 这是org.eclipse.core.runtime.Path 不是 java.nio.file.Path
猜你喜欢
  • 2018-05-20
  • 2017-01-28
  • 1970-01-01
  • 2016-02-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
相关资源
最近更新 更多