Home  >  Article  >  Java  >  Using relative paths in Java

Using relative paths in Java

巴扎黑
巴扎黑Original
2016-12-20 16:35:201596browse

During the development process, we often encounter the situation of reading configuration files. The reading of configuration files varies according to the environment and other circumstances. Generally speaking, if you use relative/path from a non-jar package, compare It’s simple, I won’t go into details here, but in many cases, we need to package our classes into jar files for use. At this time, we will find that if we did not consider these before, it may not work. Then, How to solve it? The method is as follows
:
has the following path:
Web-info--|-->classes--->conf-->config.properties
|-->lib
At this time, we need to read config .properties, when not using the jar package, it is a good method to read it as follows:
File f = new File(this.getClass().getResource("/").getPath());
f = new File(f.getPath() + "/conf/config.properties");
Note: f.getPath() is the absolute path where the class is located. For example: c:javasrcweb-infclasses
Then, by processing the file object, the configuration information can be read out. However, if the above class is added and packaged into a jar file, then when the program is executed here, the configuration will not be found. file, so what should I do with it?
The processing method is as follows:
String s_config="conf/config.properties";
InputStream in = ClassLoader.getSystemResourceAsStream(s_config);
if( in == null ){
System.out.println( "Open" + s_config + "Failed!" );
}else
{
Properties properties = new Properties();
properties.load(in);
//
//Next, you can configure it through the properties.getProperty(String obj) method Information read
}

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn