Home > Software design >  How to access files relative to the applications folder, independent of the current working director
How to access files relative to the applications folder, independent of the current working director

Time:08-06

I'm developing a Java SE 11 Maven project. In my project I have a folder called assets (it's a sibling of the src folder). This folder contains several folders and files. The whole folder has to be available at the application path - during development (in Netbeans) AND when it is deployed via an MSI package.

When running in the IDE, my assets live in <projectRoot>/assets, while my current working dir is <projectRoot>. And that's ok. I can access the assets folder via ./assets from my current working directory.

But when I deploy my application, the current working directory might be something else, but not the application folder. So accessing the assets folder via ./assets will fail.

What's the best approach in Java SE, to access a folder within the application's folder, independent of the current working directory?

Turning the assets into a resource folder is not an option, because the files must editable by the user. The assets folder has to reside directly in the file system.

CodePudding user response:

If you put your files/resources inside your source folder, you can access them through ClassName.getResource() and ClassName.getResourceAsStream() methods.

CodePudding user response:

use a config file or maven profiles (local and production) in that config or profile define a folder where the files are

old anwser: use Resources, the files in the jar (i assume your application is in a jar) will be accessible using the

URL url = Main.class.getResource("filename")

or

Inputstream stream = Main.class.getResourceAsStream("filename")

replace 'Main' with your classname

https://docs.oracle.com/javase/8/docs/technotes/guides/lang/resources.html

https://www.tutorialspoint.com/java/lang/class_getresourceasstream.htm

  •  Tags:  
  • java
  • Related