Java里经常需要查找解析配置文件,简单情况下还好,直接在ClassPath下查找即可;那么在某些复杂情况下,比如jar包内/外都有同样的配置文件时,查找策略时怎么样的呢?又如何定向查找Jar内/Jar外的配置文件呢?
在介绍查找配置文件之前,先来说下class path以及java程序的启动方式
class path
The class path is the path that the Java Runtime Environment (JRE) searches for classes and other resource files.
这是Oracle 官方对class path的说明,意思是class path是JRE搜索类和其他资源文件的路径
Java程序启动方式(Oracle JDK 8及之前版本)
Java程序都是通过java命令来启动的,可以执行一个Class文件/多个Class文件(目录)/一个Jar包/多个Jar包/多个Jar+多个Class文件(目录)的混合方式
java命令的官方手册(以下是Oracle JDK7,JDK8下有些说明不全):
Name
java - the Java application launcher
SYNOPSIS
java [ options ] class [ argument ... ]
java [ options ] -jar file.jar [ argument ... ]
options
Command-line options. See Options.
class
The name of the class to be called.
file.jar
The name of the JAR file to be called. Used only with the -jar command.
argument
The arguments passed to the main function.
OPTIONS(Standard Options)
The launcher has a set of standard options that are supported in the current runtime environment.
In addition, the current implementations of the virtual machines support a set of nonstandard options that are subject to change in future releases. See Nonstandard Options.
-classpath classpath, -cp classpath
Specifies a list of directories, JAR files, and ZIP archives to search for class files. Separate class path entries with colon