So, using this approa ch we can load resources using relative paths in a hard disk location independent manner. If you place the resources in another sub folder, then you have to specify the path relative to src/main/resources/ path. We can verify this using the following command to extract content of jar file: So, if we add a resource immediately inside this folder, during packaging, the file will be located in the immediate folder in. Usually, in Java projects resources such as configuration files, images etc. InputStream input = ("/config.properties") Here, specified relative path will work irrespective of the actual disk location the package is deployed.įollowing methods reads the file using class loader. So, best thing we can do is load the resource specifying a path relative to its class path using class loader. JVM uses class loader to load java libraries specified in class path. jar file which is the deployable unit of the project will be located here. E.g., /Users/jwithanawasam/.m2/repository) The. (In Maven, build artifacts and dependancies are stored under path given for M2_REPO class path variable. In any of the above cases, we will get java.io.FileNotFoundException error, which is a familiar exception for most java developers.Īt runtime, JVM checks the class path to locate any user defined classes and packages. Moreover, we, as developers do not have much control over JVMs current working directory. But, in a different deployment setting this may change, which leads to change the given relative path accordingly. In this scenario, it is "/Users/jwithanawasam/some_dir". However, problem with this is the relative path is depending on the current working directory, which JVM is started. This approach seems to solve the above mentioned concern. InputStream input = new FileInputStream("src/main/resources/config.properties”) So, the next option would be to use the relative file path as given below, instead of giving absolute file path: ![]() However, when ever we moved the project to another location, this path has to be changed, which is not acceptable. InputStream input = new FileInputStream("/Users/jwithanawasam/some_dir/src/main/resources/ ![]() To load a resource file such as x.properties for program use, first thing that we would consider will be specifying the absolute file path as given below:
0 Comments
Leave a Reply. |