Java 專案中的.properties檔案
阿新 • • 發佈:2019-02-16
1 建立.properties檔案
下面將檔案命名為config.properties:
檔案中的資料格式:
2 讀取檔案中的資料
可以建立一個工具類,以便實現程式碼重用,下面將工具類命名為Utils.java:
package stephen.utils;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class Utils {
public static class _property{
public static int getCountAnswer(){
Integer countAnswer = -1;
Properties properties = new Properties();
InputStream in=Utils.class.getClassLoader().getResourceAsStream("config.properties");
try {
properties.load(in);
countAnswer = Integer.valueOf(properties.get ("countAnswer").toString());
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return countAnswer;
}
public static int getcountDelLexicon(){
Integer countDelLexicon = -1 ;
Properties properties = new Properties();
InputStream in = Utils.class.getClassLoader().getResourceAsStream("config.properties");
try {
properties.load(in);
countDelLexicon = Integer.valueOf(properties.get("countDelLexicon").toString());
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
return countDelLexicon;
}
}
}
使用上述工具類讀取資料:
Integer countAnswer = Utils._property.getCountAnswer();