Get file path related to source directory

Hello,

 

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

/home/username/Projects/MyProject//test/java/com/test/MyFileTest.java

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

 

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

 

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?

 

Regards,

Aleksandr.

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