You may often encounter the need to access program configuration files in Java programs, for example, in order to be able to connect with different databases, we often deposit the information of the database connection into the property file, which generally includes the database driver class name, the database connection URL, the database username and password, and so on. In order to facilitate the installation or deployment of programs, these profiles are often stored in the root directory of the program installation. Because Java programs group classes with packages, it is sometimes better to put these profiles into the package directory where the classes that read them are located. For example, in the following illustration, it is a clear storage scenario to place the database configuration file database.properties into the package directory where the database reads the class:
/-----------Other Packages directory
|
|
-------Edu.ec.database
|
|---------------connectionpool (database connection pool Class)
|
|---------------Dao (Database Access object class)
|
|---------------daofactory (DAO's factory Class)
|
|---------------database.properties (Database Configuration Properties file)
|
|---------------Recordset (recordset Class)
In this storage scenario, all database-related classes and configuration files are in the same package directory, and in the development process, the configuration files and source files are organized in this way, making database access maintenance for the program quite clear.
Most development tools automatically put related profiles and class files into the generated destination folder or jar files when compiling a source file organization such as packaging. In general, when we publish our own Java programs, packages are published in either Jar or war format, and the corresponding configuration files are placed in the jar or war file in the same directory format, so that the configuration file and program files are packaged together for publication purposes.
The question now is, how do we read information about the configuration file located in the program installation file? For example, in the above figure, ConnectionPool is a database connection pool class that needs to automatically read database connections and configuration information stored in Database.properties at system startup to set up related database connections. In this way, we need to determine the location of the current program installation or deployment in the program in order to read the corresponding property file.