방법 1 : ServletContext를 사용하여 읽습니다
구성 파일의 RealPath를 가져온 다음 파일 스트림을 통해 읽거나 getReaasurceasstream ()을 사용하십시오.
파일 경로는 ServletContext를 사용하여 읽으므로 구성 파일은 Web-INF의 클래스 디렉토리 또는 응용 프로그램 수준 및 Web-INF 디렉토리에 배치 할 수 있습니다. Eclipse 프로젝트에서 파일 스토리지 위치의 특정 성능은 다음과 같습니다. SRC 또는 Web-Inf 및 Web Root 등에 배치 할 수 있습니다. 경로가 읽히고 파일 스트림이 읽기에 사용되므로 XML 및 속성을 포함한 구성 파일을 읽을 수 있습니다. 단점 : 서블릿 외부에서 구성 정보를 읽을 수 없습니다.
1. 먼저 동적 Javaweb 프로젝트를 만들고 프로젝트 디렉토리는 다음과 같습니다.
2. 서블릿 생성 (filereader.java)
패키지 com.xia.filereader; import java.io.fileInputStream; import java.io.ioexception; import java.io.inputstream; import java.io.inputStreamReader; import java.text.messageformat; java.util.properties import; javax.servlet.servletexception import; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; 공개 클래스 Filereader는 httpservlet {private static final long serialversionuid = 1L; 보호 된 void doget (httpservletRequest 요청, httpservletResponse 응답)은 servletexception, ioexception { /*** response.setContentType ( "text /html; charset = utf-8"); 목적은 UTF-8을 해독하기 위해 브라우저를 제어하는 것입니다. * 이런 식으로, 중국어가 없을 것입니다.*/ response.setheader ( "content-type", "text/ html; charset = utf-8"); readsrcdirpropcfgfile (응답); // db1.properties 구성 파일 응답을 읽습니다. readwebrootdirpropcfgfile (응답); // db2.properties 구성 파일 응답을 읽습니다. getwriter (). println ( "<hr/>"); readwebrootdirpropcfgfile (응답); // db2.properties 구성 파일 응답을 읽습니다. getwriter (). println ( "<hr/>"); readsrcsourcepackpropcffile (response); // src directory response.getwriter (). println ( "<hr/>") 아래 구성 디렉토리의 db3.properties 구성 파일 읽기; readwebinfpropcfgfile (response); // db4.properties 구성 파일을 읽습니다. web-inf directory} public void readsrcdirpropcfgfile (httpservletresponse responsk)에서 jdbc 디렉토리의 구성 파일을 읽습니다. inputStream in = this.getServletContext (). getResourCeasStream (Path); 속성 propss = 새로운 속성 (); props.load (in); 문자열 드라이버 = props.getProperty ( "jdbc.driver"); 문자열 url = propss.getProperty ( "jdbc.url"); 문자열 username = props.getProperty ( "jdbc.username"); 문자열 암호 = props.getProperty ( "jdbc.password"); response.getWriter (). println ( "SRC 디렉토리의 DB1.Properties 구성 파일 읽기"); response.getWriter (). println (messageformat.format ( "driver = {0}, url = {1}, username = {2}, password = {3}", driver, url, username, password); } public void readwebrootdirpropcfgfile (httpservletresponse 응답)은 ioexception {string path = "/db2.properties"; inputStream in = this.getServletContext (). getResourCeasStream (Path); 속성 propss = 새로운 속성 (); props.load (in); 문자열 드라이버 = props.getProperty ( "jdbc.driver"); 문자열 url = propss.getProperty ( "jdbc.url"); 문자열 username = props.getProperty ( "jdbc.username"); 문자열 암호 = props.getProperty ( "jdbc.password"); Response.getWriter (). println ( "Webroot 디렉토리의 DB2.Properties 구성 파일 읽기"); response.getWriter (). println (messageformat.format ( "driver = {0}, url = {1}, username = {2}, password = {3}", driver, url, username, password); } public void readsrcsourcepackpropcfgfile (httpservletresponse 응답)은 ioexception {string path = "/web-inf/classes/config/db3.properties"; String RealPath = this.getServletContext (). getRealPath (Path); inputStreamReader reader = new inputStreamReader (new FileInputStream (realPath), "UTF-8"); 속성 propss = 새로운 속성 (); props.load (독자); 문자열 드라이버 = props.getProperty ( "jdbc.driver"); 문자열 url = propss.getProperty ( "jdbc.url"); 문자열 username = props.getProperty ( "jdbc.username"); 문자열 암호 = props.getProperty ( "jdbc.password"); response.getWriter (). println ( "src 디렉토리의 config directory에서 db3.properties configuration 파일 읽기"); response.getWriter (). println (messageformat.format ( "driver = {0}, url = {1}, username = {2}, password = {3}", driver, url, username, password); } public void readwebinfpropcfgfile (httpservletresponse 응답)은 ioexception {string path = "/web-inf/jdbc/db4.properties"; String RealPath = this.getServletContext (). getRealPath (Path); System.out.println ( "RealPath :"+RealPath); System.out.println ( "ContextPath :"+this.getServletContext (). getContextPath ()); inputStreamReader reader = new inputStreamReader (new FileInputStream (realPath), "UTF-8"); 속성 propss = 새로운 속성 (); props.load (독자); 문자열 드라이버 = props.getProperty ( "jdbc.driver"); 문자열 url = propss.getProperty ( "jdbc.url"); 문자열 username = props.getProperty ( "jdbc.username"); 문자열 암호 = props.getProperty ( "jdbc.password"); response.getWriter (). println ( "Web-Inf 디렉토리의 JDBC 디렉토리의 DB4.Properties 구성 파일 읽기"); response.getWriter (). println (messageformat.format ( "driver = {0}, url = {1}, username = {2}, password = {3}", driver, url, username, password); } 보호 된 void dopost (httpservletrequest 요청, httpservletResponse 응답) servletexception, ioexception {}}3. 서블릿 구성 (web.xml)
<? xml version = "1.0"encoding = "utf-8"?> <web-app xmlns : xsi = "http://www.w3.org/2001/xmlschema-instance"xmlns = "http://java.sun.com/xml/ns/javaee" xsi : schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_3_0.xsd"3. ""webapp_ "" " <display-name> javareaderfile </display-name> <welcome-file-list> <welcome-file> index.html </welcome-file> index.htm.htm.htm.htm.htm </welcome-file> index.jsp </welcome-file> <welcome-file> default.html </welcome-file> default.htm.ht.ht.ht.ht.ht.ht.htm.htm.htm.htm.htm.htm.htm.htm.htm.ht> <welcome-file> default.jsp </welcome-file> </welcome-file-list> <servlet> <servlet-name> filereader </servlet-name> <servlet-class> com.xia.filereader.filereader </servlet> <servlet-mapping> <servlet-name> filereader </servlet-name> <Url-pattern>/filereader </url-pattern> </servlet-mapping> </web-app>
4. 테스트
방법 2 : ResourceBundle 클래스를 사용하여 구성 정보를 읽습니다
장점은 다음과 같습니다. 리소스는 완전히 자격을 갖춘 클래스 이름으로로드하여 직접 읽을 수 있으며 리소스 파일은 비 WEB 응용 프로그램에서 읽을 수 있습니다.
단점 : 클래스 SRC의 리소스 파일 만로드 할 수 있으며 .properties 파일 만 읽을 수 있습니다.
/** * 지정된 구성 파일에서 모든 데이터를 가져옵니다. * @param propertyName * Call Method : * 1. puffix * propertiesUtil.getallMessage ( "message")를 추가하지 않고 자원 소스 패키지 아래에 구성 파일을 배치합니다. * 2. 패키지에 배치 * propertiesUtil.getAllMessage ( "com.test.Message"); * @return */ public static list <string> getAllMessage (String PropertyName) {// 리소스 패키지 자원 자원 자원 자원을 가져옵니다. resourceBundle rb = resourceBundle.getBundle (propertyname.trim ()); // 모든 키 열거를 가져옵니다 <string> allkey = rb.getKeys (); // 키를 가로 지르고 값을 얻습니다. vallist = new ArrayList <string> (); while (allkey.hasmoreElements ()) {String key = allkey.nextElement (); 문자열 값 = (문자열) rb.getString (키); vallist.add (값); } return vallist; }방법 3 : 클래스 로더를 사용하여 구성 정보를 읽습니다
장점은 다음과 같습니다. 구성 리소스 정보는 WEB가 아닌 응용 프로그램에서 읽을 수 있으며 모든 리소스 파일 정보를 읽을 수 있습니다.
단점 : 클래스 SRC의 리소스 파일 만로드되며 큰 파일을로드하는 데 적합하지 않으므로 JVM 메모리 오버플로가 발생합니다.
패키지 com.xia.filereader; import java.io.bufferedReader; import java.io.ioexception; import java.io.inputstream; import java.io.inputStreamReader; java.util.properties import; 공개 클래스 readByclassloader {public static void main (String [] args)은 ioException {readPropFileByClassLoad (); } public static void readPropFileByClassLoad ()는 ioException을 던지려면 {// 구성 파일을 읽습니다. bufferedReader br = new bufferedReader (new inputStreamReader (in)); 속성 propss = 새로운 속성 (); props.load (br); for (object s : props.keyset ()) {system.out.println (s+":"+propss.getProperty (s.toString ()); }}}방법 4 : PropertiesLoaderUtils 도구 클래스
/ *** Spring에서 제공하는 PropertiesLoaderUtils ClassPath를 기반으로 파일 주소를 통해 속성 자원을 직접로드 할 수 있습니다* 가장 큰 장점은 다음과 같습니다. 구성 파일을 실시간으로로드하며 수정 후 즉시 적용됩니다. while (true) {try {props = propertiesloaderutils.loadalLproperties ( "message.properties"); for (개체 키 : props.keyset ()) {system.out.print (key+":"); System.out.println (props.get (key)); }} catch (ioexception e) {System.out.println (e.getMessage ()); } try {stride.sleep (5000);} catch (InterruptedException e) {e.printstacktrace ();}}}속성을 수정하십시오
/** * 키-값 쌍의 맵을 전달하고 속성 파일을 업데이트하고 * @param filename * 파일 이름 (리소스 소스 패키지 디렉토리에 배치)을 업데이트하고 접미사 * @param keyvaluemap * key-keyvaluemap */public static void updateproperties (문자열, 문자열, 문자열> keyvaluemap) {// getresource teret it utf-the getresource tetter it ut ut uk valuemap이 필요합니다. 경로 정보. 경로에 중국어와 공간이 있으면이 캐릭터를 변환합니다. 이런 식으로, 결과는 종종 우리가 원하는 실제 경로가 아닙니다. 여기서 UrlDecoder Decode 방법은 원래 중국어 및 우주 경로를 얻기 위해 해독하도록 호출됩니다. 문자열 filepath = propertiesutil.class.getClassLoader (). getResource (filename) .getFile (); 속성 소품 = null; 완충 작가 bw = null; try {filepath = urldecoder.decode (filepath, "utf-8"); log.debug ( "UpdateProperties PropertiesPath :" + filepath); props = propertiesloaderutils.loadProperties (new classPathResource (filename)); log.debug ( "UpdateProperties PropertiesPath :" + filepath); props = propertiesloaderutils.loadProperties (new classPathResource (filename)); log.debug ( "UpdateProperties old :"+props); // 속성 파일 쓰기 bw = new BufferedWriter (new outputStreamWriter (new FileOutputStream (Filepath))); props.clear (); // (문자열 키 : keyvaluemap.keyset ()) props.setProperty (key, keyValuemap.get (key)); log.debug ( "UpdateProperties new :"+propss); props.store (bw, ""); } catch (ioexception e) {log.error (e.getMessage ()); } 마침내 {try {bw.close (); } catch (ioexception e) {e.printstacktrace (); }}}요약
위는 Javaweb의 구성 파일을 읽는 4 가지 방법입니다. 나는 그것이 당신에게 도움이되기를 바랍니다. 궁금한 점이 있으면 메시지를 남겨 주시면 편집자가 제 시간에 답장을 드리겠습니다. Wulin.com 웹 사이트를 지원해 주셔서 대단히 감사합니다!