ホームページ  >  記事  >  Java  >  Javaバックグラウンド読み取り構成ファイル

Javaバックグラウンド読み取り構成ファイル

巴扎黑
巴扎黑オリジナル
2016-12-10 09:44:461928ブラウズ

数日前に開発中に問題が発生しました。バックグラウンドで設定ファイルを読み込むときに、属性値を読み取れなかったので、ここで共有します。

最初にコードを添付します。


パッケージ com.shafei.util;
import java.io.FileInputStream;
import java.io.OutputStream; ;
インポート java.util.Enumeration;
インポート org.apache.log4j.Logger;
プライベート静的ロガー レコード = Logger.getLogger(PropertieUtil.class); () {
}
/ **
*設定ファイルの特定のプロパティを読み取ります
* /
Public static string readValue (String file path, String key) {
Property props = new feature ()
Try {
/ /パスが / で始まることに注意してください。そうでない場合は、それを処理します
If (filePath.startsWith("/")!)
ファイル パス = "/" + ファイル パス
InputStream time = PropertieUtil.class.getResourceAsStream(ファイル パス; );
props.load(in);
文字列値 = props.getProperty(key);
戻り値
}
/ **
*設定ファイルの内容全体を出力します (ファイルパス、設定ファイル名、パスがある場合は props/test.properties)
* /
Public static void readProperties (String file path) {
Properties props = New features();
Try {
//パスが / で始まることに注意してください、それ以外の場合は .class.getResourceAsStream(file path);
enumeration EN = props.propertyNames(); ? >;
//印刷中のトラバース
(en.hasMoreElements()) {
String key = (String) en.nextElement();
String property = props.getProperty(key); );
logger.info (key + ":" + property);
}
} catch (例外 5) {
logger.error (E)
}
}
/ **
* が書き込まれます構成ファイルに
* /
Public static valid writeProperties (string file name, stringparameter name, stringparameterValue) throws anException {
//Maven プロジェクトの場合は、ターゲットに移動してください。ソースコードではなく、ディレクトリ内のファイルを表示します
//パスに / を追加できないことに注意してください。追加された場合は削除してください
, if (fileName.startsWith ("/"))
fileName.substring ( 1);
文字列 ファイルパス = getPath() + PropertyUtil.class.getResource("/") のファイル名。
// 設定ファイルを取得します
Property PPS = new features();
in InputStream(new FileInputStream(file path));
out OutputStream = new FileOutputStream; (ファイルパス);
//設定名と値を設定します
pps.setProperty (パラメータ名,parameterValue);
//ファイルコメントと等しいコメント設定
pps.store (フルスコア, "update" + パラメータ名 + "name ");
out.flush();
out.close();
}
public static void main(String[] args) throws Exception {
readProperties("jdbc.properties" );
logger.info(readValue( "jdbc.properties", "JAVABLOG_WRITE_URL"));
// writeProperties("CONF/test.properties", "dataSource.driver", "test");
}

私も専門家から上記のコードを学びました。これは難しくなく、非常に実用的です。皆さんのお役に立てれば幸いです。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。