java - Standard/Uniform way to locate files inside and outside JAR file? -
what uniform or standard way locate , access files inside , outside jar files.
i have injarclass() defined in jar file contains configuration text files. extend class in host project have more configurations.
let have inside jar :
config/default.conf
then in host project :
class myclass extends injarclass { .... }
and :
config/test.conf
then run :
xenv=test java myclass
the whole configuration process happens inside injarclass(), based on environment xenv. see injarclass() have access both :
<jar>/config/default.conf <host_app_dir>/config/test.conf
so repeat question there uniform way access both, if directory structure mirror each other.
if place both current directory , .jar file in classpath:
xenv=test java -classpath .:myjarfile.jar myclass
you can this:
string configfile = "/config/" + system.getenv().getordefault("xenv", "default") + ".conf"; inputstream config = myclass.class.getresourceasstream(configfile); if (config == null) { throw new filenotfoundexception( "cannot locate " + configfile + " in classpath"); }
this works because application resource resource java searches within each location in classpath. getresourceasstream first search requested path relative first classpath location, .
. if not find file name, @ second classpath location, myjarfile.jar
, , seeing .jar file, search requested file inside .jar.
Comments
Post a Comment