John Doe
John Doe

Reputation: 1138

Get the workspace root

I am developing an eclipse plugin and I am trying to get the workspace root in order to acces later a file from the workspace and read something from it.

I skipped the error handling for a shorter code

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...

The problem is that the implemnted getProject method returns itself for projects or null for the project root.

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

path.segment(0)) contains the workspace root

Am I over complicating things here? How could I achieve this in another way?

Upvotes: 0

Views: 1325

Answers (1)

greg-449
greg-449

Reputation: 111142

You get the IFile for a path in the workspace using:

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

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

IFile file = root.getFileForLocation(path);

To read the contents of a file in the workspace you should use IFile.getContents:

InputStream is = file.getContents();

Use IFile.getCharset to get the character set of a text file:

String charset = file.getCharset();

So a Reader for the file would be:

Reader reader = new InputStreamReader(is, charset);

Note that Path is org.eclipse.core.runtime.Path

Upvotes: 2

Related Questions