In web development, there will inevitably be some fixed parameters, we generally put these fixed parameters in the properties file, and then use the time to read out. But often there are some errors, the corresponding path can not be found, so, today specifically about how to get the path correctly.
First, we want to deploy the properties file in the $app/web-inf/classes folder, for example, when the Info.properties file is placed under the Dingding WEB application, the path of the file is $dingding/ Web-inf/classes/info.properties.
It is then read in two cases:
(i) Read in the Servlet class
There are two ways to read:
1. Directly read the properties file into the stream
[Java]View PlainCopy
- InputStream in = Request. Getservletcontext (). getResourceAsStream ("/web-inf/classes/info.properties");
- Properties prop = new properties ();
- Prop.load (in);
- Prop.getproperty ("username");
2. Obtain the path to the properties file, and then read the
[Java]View PlainCopy
- String path = Request. Getservletcontext (). Getrealpath ("/web-inf/classes/info.properties");
- FileInputStream in = new FileInputStream (path);
- Properties prop = new properties ();
- Prop.load (in);
- Prop.getproperty ("username");
The second method is recommended and easy to understand.
(ii) Read in non-servlet classes (in normal Java classes)
There are also two ways of reading:
1. Load files directly into memory
[Java]View PlainCopy
- InputStream in = Demo. Class.getclassloader (). getResourceAsStream ("db.properties");
- Properties prop = new properties ();
- Prop.load (in);
- Prop.getproperty ("username");
But there are some flaws: when the class loader loads the content, it will first look for the content in memory, if there is no longer loaded directly in memory, so this method, after the first load, if the contents of the file changes, after the second load or the original content, can not load the modified content. The method below takes the absolute path of the file to load without this problem.
2. Read the path to the file and read it with a stream
[Java]View PlainCopy
- String Path = Demo. Class.getclassloader (). GetResource ("Info.properties"). GetPath ();
- FileInputStream in = new FileInputStream (path);
- Properties prop = new properties ();
- Prop.load (in);
- Prop.getproperty ("username");
The above is an absolute path when using FileInputStream, and a relative path can be used:
Common Java Engineering: is the path relative to the current class
Web Engineering: is a path name relative to $tomcat/bin ($tomcat Tomcat)
Source: http://blog.csdn.net/jeryjeryjery/article/details/53257921
Path issues when reading the properties file in the Java Web