執行此操作的代碼非常簡單。讓我們考慮一下,你有一個名爲SampleApp.war
戰爭文件,其中有一個屬性文件名爲myApp.properties
在它的根:
SampleApp.war
|
|-------- myApp.properties
|
|-------- WEB-INF
|
|---- classes
|
|----- org
|------ myApp
|------- MyPropertiesReader.class
讓我們假設你想讀一個名爲abc
存在於性能屬性文件:
在myApp.properties
:
abc = someValue;
xyz = someOtherValue;
讓我們考慮存在於你的應用程序的類org.myApp.MyPropertiesReader
想讀的財產。下面是相同的代碼:
package org.myapp;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
/**
* Simple class meant to read a properties file
*
* @author Sudarsan Padhy
*
*/
public class MyPropertiesReader {
/**
* Default Constructor
*
*/
public MyPropertiesReader() {
}
/**
* Some Method
*
* @throws IOException
*
*/
public void doSomeOperation() throws IOException {
// Get the inputStream
InputStream inputStream = this.getClass().getClassLoader()
.getResourceAsStream("myApp.properties");
Properties properties = new Properties();
System.out.println("InputStream is: " + inputStream);
// load the inputStream using the Properties
properties.load(inputStream);
// get the value of the property
String propValue = properties.getProperty("abc");
System.out.println("Property value is: " + propValue);
}
}
[Java中讀取屬性文件]中
可能重複(http://stackoverflow.com/questions/8285595/reading-properties-file-in-java) – vzamanillo