How can I get a VirtualFile from a path relative to 'workspace'?

I need a method:  VirtualFile getFile(String path)
And need to use it like this: getFile("/Module1/src/package1/file1").
How can this be done in Intellij IDEA?

7 comments
Comment actions Permalink

There's no 'workspace' concept in IntelliJ IDEA. See
com.intellij.openapi.project.Project#getBaseDir(), getBasePath()

com.intellij.openapi.module.Module#getModuleFile(), getModuleFilePath()
com.intellij.openapi.vfs.LocalFileSystem#findFileByPath(),
com.intellij.openapi.vfs.VfsUtilCore#findRelativeFile()
etc.

1
Comment actions Permalink

I know workspace concept dosn't exist that's way i used quote. But the question remains, how can i get the VirtualFile from that String?
In eclipse it can be done like this:

public Object getFile(String path) {
        return ResourcesPlugin.getWorkspace().getRoot().findMember(path);
    }

0
Comment actions Permalink

Did you look at the methods I listed? I think it is possible to guess an answer even without looking in docs for those methods, just by reading the names.

0
Comment actions Permalink

Project.getBaseDir()is of no use, because it returns the parent directory of the .ipr file. And i can have Module1 in C: and Module2 in D: (Module1 has nothing in common with the .ipl file path)

0
Comment actions Permalink

To find required module use ModuleManager.
Module file (*.iml) and module content roots can be located on different drives as well, so you'll probably need to get content or source roots using ModuleRootManager.

0
Comment actions Permalink

I haven't found a nice solution to work with relative path. So i used Alexander Doroshko sugetions and absolute paths.

0
Comment actions Permalink
VirtualFile[] vFiles = ProjectRootManager.getInstance(this.project).getContentRoots();


VirtualFile stateMachineConfig = vFiles[0].findChild("stateConfig.json");

or

VirtualFile controllerFolder = vFiles[0].findFileByRelativePath("scripts/hov/controller");
0

Please sign in to leave a comment.