1. 程式人生 > 其它 >讀取properties的幾種方式

讀取properties的幾種方式

讀取properties的幾種方式

  • 方法①
public class ResourceUtil {
private static final ResourceBundle bundle = java.util.ResourceBundle
.getBundle("sysConfig");
public static final String getConfigByName(String name) {
String value = "";
try {
value = new String(bundle.getString(name).getBytes("iso8859-1"
), "UTF-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return value; } }
  • 方法②
public void testPro() throws IOException{
InputStream insss =this.getClass().getResourceAsStream("/conf/resources.properties");
Properties pss = new Properties();
pss.load(insss);
System.
out.println(pss.getProperty("IMAGE_SERVER_URL")); }
  • 方法③:
public void testPro() throws IOException{
InputStream insss =Object.class.getResourceAsStream("/conf/resources.properties");
Properties pss = new Properties();
pss.load(insss);
System.out.println(pss.getProperty("IMAGE_SERVER_URL"
)); }
  • 方法④:
public class testProperties extends TestCase{
public void testPro() throws IOException{
Resource resource = new ClassPathResource("/conf/resources.properties");
Properties props = PropertiesLoaderUtils.loadProperties(resource);
System.out.println(props.getProperty("IMAGE_SERVER_URL"));
}
}
  • 方法⑤

xml配置檔案中引入的:

        <context:property-placeholder location="classpath:conf/resources.properties" />  




       @Value("${IMAGE_SERVER_URL}")  

       private String IMAGE_SERVER_URL;
  • 方法⑥:
ResourceBundle的方式 ,傳入一個inStream
ResourceBundle resource = new PropertyResourceBundle(inStream);
  • 方法⑦:通過檔案讀取
InputStream inStream = new FileInputStream(new File("filePath"));
  • 方法⑧:在servlet中:
InputStream in = context.getResourceAsStream("filePath");

方法⑨:ulr方式讀取

URL url = new URL("path");
InputStream inStream = url.openStream();
  • 方法10讀取的方式:
Properties prop = new Properties();
prop.load(inStream);
String key = prop.getProperty("username");
String key = (String) prop.get("username");