Java读取properties文件 【转】

来源:互联网 发布:卫星免费网络电视直播 编辑:程序博客网 时间:2024/04/29 10:59
Java读取properties文件 【转】

使用J2SE API读取Properties文件的六种方法

1。使用java.util.Properties类的load()方法
示例: InputStream in = lnew BufferedInputStream(new FileInputStream(name));
Properties p = new Properties();
p.load(in);

2。使用java.util.ResourceBundle类的getBundle()方法
示例: ResourceBundle rb = ResourceBundle.getBundle(name, Locale.getDefault());

3。使用java.util.PropertyResourceBundle类的构造函数
示例: InputStream in = new BufferedInputStream(new FileInputStream(name));
ResourceBundle rb = new PropertyResourceBundle(in);

4。使用class变量的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

5。使用class.getClassLoader()所得到的java.lang.ClassLoader的getResourceAsStream()方法
示例: InputStream in = JProperties.class.getClassLoader().getResourceAsStream(name);
Properties p = new Properties();
p.load(in);

6。使用java.lang.ClassLoader类的getSystemResourceAsStream()静态方法
示例: InputStream in = ClassLoader.getSystemResourceAsStream(name);
Properties p = new Properties();
p.load(in);

补充

Servlet中可以使用javax.servlet.ServletContext的getResourceAsStream()方法
示例:InputStream in = context.getResourceAsStream(path);
Properties p = new Properties();
p.load(in);

 例子:

package other;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Enumeration;
import java.util.Properties;

public class TestProperoties {
 
 public static void main(String[] args) {
  
  Properties prop = new Properties();
  try {
   FileInputStream fis = new FileInputStream("prop.properties");// 属性文件流
   prop.load(fis);// 将属性文件流装载到Properties对象中
   fis.close();// 关闭流
   // 获取属性值,sitename已在文件中定义
   
   Enumeration en = prop.propertyNames();
   while (en.hasMoreElements()) {
    String key = (String) en.nextElement();
    String Property = prop.getProperty(key);
    System.out.println(key+":" + Property);
   }
   
   // 修改sitename的属性值
   prop.setProperty("sitename", "Boxcode");
   // 添加一个新的属性studio
   prop.setProperty("studio", "Boxcode Studio");
   // 文件输出流
   FileOutputStream fos = new FileOutputStream("prop.properties");
   // 将Properties集合保存到流中
   prop.store(fos, "Copyright (c) Boxcode Studio");
   fos.close();// 关闭流

  } catch (FileNotFoundException e) {
   e.printStackTrace();
  } catch (IOException e) {
   e.printStackTrace();
  }
 }

}

 

prop.properties

siteurl=www.csdn.com  
sitename=abc