intellij-ideaintellij-idea-2016

How can I reference the IntelliJ project path in my code?


I have a text file in my project and need to read its contents:

private final static String SOURCE_FILE = "C:/Project/resources/Source.txt";

Is it possible to use an IntelliJ variable?

private final static String SOURCE_FILE = "${ProjectDir}/resources/Source.txt";

I want to avoid hardcoding a path in my code.


Solution

  • In most circumstances, what you should do instead is put the file into a resources directory of your project/module (src/main/resources will work by default, you can create it if it doesn't exist) and access it using methods getResource or getResourceAsStream on Class and ClassLoader. See Accessing Resources guide from Oracle.

    The major exception is if you need to pass this file to an external program.