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

1.2k views Asked by At

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.

2

There are 2 answers

1
Alexey Romanov On BEST ANSWER

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.

2
jovi De Croock On

For example if you added a folder audio to your project structure then you could acces it like this:

new File(".\\Audio\\MyAudioFile.mp3")

Good luck, if you have any questions feel free to shoot 'em in comments :)