1

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.

Roland
  • 7,525
  • 13
  • 61
  • 124

2 Answers2

1

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 :)

jovi De Croock
  • 595
  • 2
  • 8
  • Because your java code looks at your source folder as if it's the only one, he lives in the source folder, it would behave differentley if you would for example say private final static String SOURCE_FILE = "C:/Project/resources/Source.txt"; – jovi De Croock Nov 15 '17 at 08:12
  • That's not the real reason. Java code doesn't know about its source; this path is relative to the _working directory_, and when you run code from IDEA it will set the project directory as the working directory by default, which you can change. – Alexey Romanov Nov 15 '17 at 08:16
1

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.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487