のパッケージ構造に埋め込まれているプロパティ ファイルを読み取る必要がありますcom.al.common.email.templates
。
私はすべてを試しましたが、それを理解することはできません。
最終的に、私のコードはサーブレット コンテナーで実行されることになりますが、コンテナーには何の依存もしたくありません。私は JUnit テスト ケースを作成しており、両方で動作する必要があります。
のパッケージ構造に埋め込まれているプロパティ ファイルを読み取る必要がありますcom.al.common.email.templates
。
私はすべてを試しましたが、それを理解することはできません。
最終的に、私のコードはサーブレット コンテナーで実行されることになりますが、コンテナーには何の依存もしたくありません。私は JUnit テスト ケースを作成しており、両方で動作する必要があります。
パッケージ内のクラスからプロパティをロードするときにcom.al.common.email.templates
使用できます
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
(必要なすべての例外処理を追加します)。
クラスがそのパッケージに含まれていない場合は、InputStream を少し異なる方法で取得する必要があります。
InputStream in =
getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
/ 内の相対パス (先頭に「/」がないもの) はgetResource()
、getResourceAsStream()
クラスが含まれるパッケージを表すディレクトリを基準にしてリソースが検索されることを意味します。
を使用すると、クラスパス上java.lang.String.class.getResource("foo.txt")
の (存在しない) ファイルが検索されます。/java/lang/String/foo.txt
絶対パス (「/」で始まるパス) を使用すると、現在のパッケージは無視されます。
Joachim Sauer の回答に追加するには、静的なコンテキストでこれを行う必要がある場合は、次のようなことができます。
static {
Properties prop = new Properties();
InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
prop.load(in);
in.close()
}
(以前と同様、例外処理は省略されています。)
public class Test{
static {
loadProperties();
}
static Properties prop;
private static void loadProperties() {
prop = new Properties();
InputStream in = Test.class
.getResourceAsStream("test.properties");
try {
prop.load(in);
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public class ReadPropertyDemo {
public static void main(String[] args) {
Properties properties = new Properties();
try {
properties.load(new FileInputStream(
"com/technicalkeeda/demo/application.properties"));
System.out.println("Domain :- " + properties.getProperty("domain"));
System.out.println("Website Age :- "
+ properties.getProperty("website_age"));
System.out.println("Founder :- " + properties.getProperty("founder"));
// Display all the values in the form of key value
for (String key : properties.stringPropertyNames()) {
String value = properties.getProperty(key);
System.out.println("Key:- " + key + "Value:- " + value);
}
} catch (IOException e) {
System.out.println("Exception Occurred" + e.getMessage());
}
}
}
ロードメソッドを介してPropertiesクラスを使用すると仮定すると、入力ストリームを取得するために ClassLoader getResourceAsStreamを使用していると思います。
名前をどのように渡していますか。次の形式にする必要があるようです。/com/al/common/email/templates/foo.properties
この呼び出しでこの問題を解決できました
Properties props = PropertiesUtil.loadProperties("whatever.properties");
さらに、whatever.properties ファイルを /src/main/resources に配置する必要があります。
以下のコードを使用してください:
プロパティ p = new Properties();
StringBuffer パス = 新しい StringBuffer("com/al/common/email/templates/");
path.append("foo.properties");
入力ストリーム fs = getClass().getClassLoader()
.getResourceAsStream(path.toString());
if(fs == null){
System.err.println("Unable to load the properties file");
}
else{
try{
p.load(fs);
}
catch (IOException e) {
e.printStackTrace();
}
}