方法1:ServletContextを使用して読み取ります
構成ファイルのRealPathを取得してから、ファイルストリームを介して読み取るか、メソッドgetReaasurceasStream()を使用します。
ファイルパスはServletContextを使用して読み取られるため、構成ファイルはWeb-INFのクラスディレクトリ、またはアプリケーションレベルとWeb-INFディレクトリに配置できます。 Eclipseプロジェクトのファイルストレージ場所の特定のパフォーマンスは次のとおりです。SRCまたはWeb-INFやWeb-Rootなどの下に配置できます。パスが読み取られ、ファイルストリームが読み取りに使用されるため、XMLやプロパティなどの構成ファイルを読み取ることができます。短所:サーブレットの外側の構成情報を読み取ることができません。
1.最初に動的なJavawebプロジェクトを作成します。プロジェクトディレクトリは次のとおりです。
2。サーブレットを作成する(filereader.java)
パッケージcom.xia.filereader; java.io.fileinputStreamをインポートします。 java.io.ioexceptionをインポートします。 java.io.inputStreamをインポートします。 java.io.inputStreamReaderをインポートします。 java.text.messageformatをインポートします。 java.util.propertiesをインポートします。 javax.servlet.servletexceptionをインポートします。 javax.servlet.http.httpservletをインポートします。 javax.servlet.http.httpservletrequestをインポートします。 javax.servlet.http.httpservletResponseをインポートします。 Public Class FileReaderはhttpservletを拡張します{private static final long serialversionuid = 1l;保護されたvoid doget(httpservletrequest request、httpservletresponse応答)servletexception、ioexception { /*** respons.setContentType( "text /html; charset = utf-8");目的は、ブラウザを制御してUTF-8をデコードすることです。 *このようにして、中国語の文字化けはありません*/ response.setheader( "content-type"、 "text/ html; charset = utf-8"); readsrcdirpropcfgfile(response); // db1.properties configuration file response.getwriter()。println( "<hr/>>"); readwebrootdirpropcfgfile(response); // db2.properties configuration file response.getwriter()。println( "<hr/>"); readwebrootdirpropcfgfile(response); // db2.properties configuration file response.getwriter()。println( "<hr/>"); readsrcsourcepackpropcfgfile(response); // src directory respons.getwriter()。println( "<hr/>"); readwebinfpropcfgfile(response); // web-infディレクトリの下のjdbcディレクトリのdb4.properties構成ファイルを読み取り} public void readsrcdirpropcfgfile(httpservletresponse応答)を読み取ります。 inputStream in = this.getServletContext()。getResourceAsStream(PATH); Properties Props = new Properties(); props.load(in); string driver = props.getProperty( "jdbc.driver"); string url = props.getProperty( "jdbc.url"); string 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応答)throws ioexception {string path = "/db2.properties"; inputStream in = this.getServletContext()。getResourceAsStream(PATH); Properties Props = new Properties(); props.load(in); string driver = props.getProperty( "jdbc.driver"); string url = props.getProperty( "jdbc.url"); string 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応答)throws ioexception {string path = "/web-inf/classes/config/db3.properties"; string realpath = this.getServletContext()。getRealPath(PATH); inputStreamReader reader = new inputStreamReader(new FileInputStream(RealPath)、 "UTF-8"); Properties Props = new Properties(); propss.load(reader); string driver = props.getProperty( "jdbc.driver"); string url = props.getProperty( "jdbc.url"); string username = props.getProperty( "jdbc.username");文字列パスワード= props.getProperty( "jdbc.password"); Response.getWriter()。println( "srcディレクトリの下の構成ディレクトリでdb3.properties構成ファイルを読み取ります"); response.getWriter()。println(messageformat.format( "driver = {0}、url = {1}、username = {2}、password = {3}"、driver、url、username、password)); } public void readwebinfpropcfgfile(httpservletresponse応答)throws 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"); Properties Props = new Properties(); propss.load(reader); string driver = props.getProperty( "jdbc.driver"); string url = props.getProperty( "jdbc.url"); string 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 request、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/nns/javaee xsi:schemalocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/ns/javaee/web-app_0.0.0.xsd" "id" "id" id "id" webaee/wweb-app_0.xsdd <display-name> javareaderfile </display-name> <welcome-file-list> <welcome-file> index.html </welcome-file> <welcome-file> index.htm </welcome-file> <welcome-file> index.jsp </welcome-file> <welcome-file> default.html> welcome-file> <welcome file <welcome-file> default.jsp </welcome-file> </welcome-file-list> <servlet> <servlet-name> fileReader </servlet-name> <servlet-class> com.xia.filereader.filereader </servlet-class> </servlet> <servlet-name> filereader </servlet-name> <url-pattern>/filereader </url-pattern> </servlet-mapping> </web-app>
4。テスト
方法2:ResourceBundleクラスを使用して、構成情報を読み取ります
利点は次のとおりです。リソースは、完全に適格なクラス名にロードして直接読み取ることができ、リソースファイルは非WEBアプリケーションで読み取ることができます。
短所:クラスSRCの下のリソースファイルのみをロードでき、.propertiesファイルのみを読み取ることができます。
/** *指定された構成ファイルですべてのデータを取得 * @param propertyname *コールメソッド: *1。接尾辞を追加せずにリソースソースパッケージの下に構成ファイルを配置します * 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()を取得します。 //キーをトラバースして値リスト<String> vallist = new ArrayList <String>(); while(allkey.hasmoreElements()){string key = allkey.nextelement(); string value =(string)rb.getString(key); vallist.add(value); }バリストを返します。 }方法3:クラスローダーを使用して、構成情報を読み取ります
利点は次のとおりです。構成リソース情報は、非WEBアプリケーションで読み取ることができ、リソースファイル情報を読み取ることができます。
短所:クラスSRCの下のリソースファイルのみがロードされ、大きなファイルのロードには適していません。
パッケージcom.xia.filereader; java.io.bufferedreaderをインポートします。 java.io.ioexceptionをインポートします。 java.io.inputStreamをインポートします。 java.io.inputStreamReaderをインポートします。 java.util.propertiesをインポートします。 public class readbyclassloader {public static void main(string [] args)throws ioexception {readpropfilebyclassload(); } public static void readpropfilebyclassload()throws ioexception {//構成ファイルdb3.properties inputstream in = readbyclassloader.class.getClassLoader()。 BufferedReader br = new BufferedReader(new inputstreamReader(in)); Properties Props = new Properties(); propss.load(br); for(object s:propss.keyset()){system.out.println(s+":"+props.getProperty(s.toString())); }}}方法4:PropertiesLoaderUtilsツールクラス
/ *** Springが提供するPropertiesLoaderUtilsを使用すると、クラスパスに基づいてファイルアドレスを介してプロパティリソースを直接ロードできます*最大の利点は、構成ファイルをリアルタイムでロードすることです。 while(true){try {props = propertiesloaderutils.loadallproperties( "message.properties"); for(オブジェクトキー:propss.keyset()){system.out.print(key+":"); system.out.println(props.get(key)); }} catch(ioException e){system.out.println(e.getmessage()); } try {thread.sleep(5000);} catch(arternedexception e){e.printstacktrace();}}}}プロパティを変更します
/** *キー値ペアのマップを渡し、プロパティファイル * * @param filename *ファイル名(リソースソースパッケージディレクトリに配置)を更新します。@param keyvalueemap * key-valueペアマップ */public static void updateproperties(string filename、map <<string、string> keyvaluemap> keyvaluemap> keyvaluemap)パスに中国とスペースがある場合、これらのキャラクターを変換します。このようにして、結果は私たちが望む本当の道ではないことがよくあります。ここでは、urldeCoderデコード法が呼び出され、デコードして元の中国とスペースパスを取得します。 string filepath = propertiesutil.class.getClassLoader()。getResource(filename).getFile();プロパティプロップ= null; bufferedwriter 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))); propss.clear(); //古いファイルを(文字列キー:keyvaluemap.keyset())propssproperty(key、keyvaluemap.get(key)); log.debug( "updateProperties new:"+props); props.store(bw、 ""); } catch(ioexception e){log.error(e.getmessage()); }最後に{try {bw.close(); } catch(ioexception e){e.printstacktrace(); }}}要約します
上記は、編集者が紹介するJavawebによる構成ファイルを読み取る4つの方法です。それがあなたに役立つことを願っています。ご質問がある場合は、メッセージを残してください。編集者は時間内に返信します。 wulin.comのウェブサイトへのご支援ありがとうございます!