Get file path related to source directory



I need to get source file path related to current source directory. For example, if I have Maven project with path:


I need to get "/com/test/".


But if will be simple Java Project with path: /home/username/Projects/MyProject/src/com/test/


In this case I also need to get "/com/test/".


I made it via:

PsiDirectory psiFileParent = psiFile.getParent();
ItemPresentation presentation = PsiDirectory.class.cast(psiFileParent).getPresentation();
String locationString = presentation.getLocationString();


But this approach don't work for PyCharm projects (or for GoLand).


Can you, please, help me?




Official comment

psiFile.getVirtualFile() will give you a VirtualFile (not-null for physical files).

Then, ProjectFileIndex.SERVICE.getInstance().getContentRootForFile(or getSourceRootForFile) will get you a corresponding root. Finally, you can use VfsUtilCore.getRelativePath to get the relative path between two files.

Please sign in to leave a comment.