Java的Properties類和讀取.properties文件


一、.properties文件的作用

  Properties屬性文件在JAVA應用程序中是經常可以看得見的,也是特別重要的一類文件。它用來配置應用程序的一些信息,不過這些信息一般都是比較少的數據,沒有必要使用數據庫文件來保存,而使用一般的文本文件來保存,如果是通過File直接保存的話,可能在存儲和讀取上都不是很方便,但如果保存為Properties文件就不一樣了,屬性文件都有鍵值對應的,在JAVA的包中,有提供專門的操作屬性文件的類。這個類就是 java.uitl.Properties類,由於Properties類是一個集合類,所以,Properties會將屬性以集合的方式讀寫。(配置文件有兩種:XML和.properties文件)

  在Java中,.properties文件的內容格式是"鍵-值"的格式,文本的注釋信息可以用"#"來注釋。

二、Java Properties類

Properties類繼承自Hashtable,如下:

 

它提供的主要方法:

  1. getProperty(String key):用指定的鍵在此屬性列表中搜索屬性。也就是通過key得到對應的value
  2. load(InputStream inStream):通過對指定文件進行裝載來獲得(鍵-值)對,以供getProperty()調用。
  3. setProperty(String key,String value):調用基類的put方法來設置鍵-值對
  4. store(OutPutStream out,String comments):將鍵-值對按照文件的格式寫入到指定文件中
  5. clear():清除所有轉載的鍵-值對

三、寫.properties文件

默認情況下,空格可以作為Properties文件中Key和Value的分隔符,當我們需要在Key中使用空格的時候,可以使用反斜杠(\)對空格進行轉移。注: 斜杠為(/),反斜杠為(\)。

盡量少使用等號和空格。一定要注意使用空格。在每行的末尾盡量不要使用空格。

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/userdate
username=root
password=root

如果在userdate后邊加一個空格保存,程序運行時候就會提示userdate不存在

四、java web 讀取.properties文件

db.properties

url = "jdbc:mysql://localhost:3306/test"
username="root"
name="root"

第一種:使用ServletContext的getResourceAsStream方法:返回資源文件的讀取字節流

 

public  void test1() throws IOException{
        InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
        Properties props=new Properties();
        props.load(in);
        String url=props.getProperty("url");
        String username=props.getProperty("username");
        String password=props.getProperty("password");
        
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
    }

 this.getClass().getClassLoader().getResource 的詳解:

  • 調用對象的getClass()方法是獲得對象當前的類類型
  • 在類類型上調用getClassLoader()方法是得到當前類型的類加載器
  • 最后調用了類加載器的getResourceAsStream()方法來加載資源。

第二種:使用ServletContext的getRealPath方法,獲得文件的完整絕對路徑path,再使用字節流讀取path下的文件

 

public void test2() throws IOException{
        String path =this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");
        FileInputStream in=new FileInputStream(path);
     ////相比第一種方法的好處是:除了可以獲取數據,還可以獲取資源文件的名稱
        String filename=path.substring(path.lastIndexOf("\\")+1);
        System.out.println(filename);
        Properties props=new Properties();
        props.load(in);
        String url=props.getProperty("url");
        String username=props.getProperty("username");
        String password=props.getProperty("password");
        System.out.println(url);
        System.out.println(username);
        System.out.println(password);
    }

第三種:類加載器:

 

        /*
             * 使用類路徑的讀取方式:
             *   /  :斜杠標示classpath的根目錄
             *      在java項目下:classpath的根目錄從bin開始
             *      在web 項目下:classpath的根目錄從WEB-INF/classes目錄開始
             */
            //讀取db.properties文件
            Properties props=new Properties();
            InputStream in= JdbcUtil.class.getResourceAsStream("/db.properties");
            props.load(in);
            url=(String) props.get("url");
            user=props.getProperty("user");
            password=props.getProperty("password");
            driverClass=props.getProperty("driverClass");

 

五、Java操作Properties類

Properties(配置文件類):主要用於生產配置文件與讀取配置文件的信息。

  1. 要注意的細節:如果配置文件的信息一旦使用了中文,那么在使用store方法,生成配置文件的時候只能使用字符流解決,如果使用字節流生成配置文件,默認使用的是ISO8859-1碼表進行編碼存儲,這時候會出現亂碼
  2. 如果Properties中的內容發生了變化,一定要重新
//讀取配置文件的信息
    public static void readProperties() throws FileNotFoundException, IOException{
        //創建Properties
        Properties properties=new Properties();
        //加載配置文件
        properties.load(new FileReader("F:\\user.properties"));
        Set<Entry<Object, Object>> entrys=properties.entrySet();
        //遍歷Properties
        for(Entry<Object,Object> entry:entrys){
            System.out.println("鍵:"+entry.getKey()+" 值:"+entry.getValue());
        }
        //更新配置文件
        properties.setProperty("校長", "345");
        properties.store(new FileWriter("F:\\user.properties"), "用戶");
    }
    //保存配置文件的信息
    public static void createProperties() throws FileNotFoundException, IOException{
        //創建Properties
        Properties properties=new Properties();
        properties.setProperty("校長", "123456");
        properties.setProperty("撒個", "123456");
        properties.setProperty("個長", "123456");
        //遍歷Properties
        Set<Entry<Object, Object>> entrys=properties.entrySet();
        for(Entry<Object,Object> entry:entrys){
            System.out.println("鍵:"+entry.getKey()+" 值:"+entry.getValue());
        }
        //保存Properties
        properties.store(new FileWriter("F:\\user.properties"), "用戶");
        
    }

六、練兵場地

package cn.lyjs.other;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
/*
 * 軟件使用超過三次,提示購買正版軟件
 */
public class Demo2 {
        public static void main(String[] args) throws IOException {
            File file =new File("F:\\count.properties");
            if(!file.exists()) file.createNewFile();
            //創建Properties對象
            Properties proterties=new Properties();
            proterties.load(new FileInputStream(file));
            
            int count=0;//記錄訪問的次數
            String value=(String) proterties.get("count");
            if(value!=null){
                count=Integer.parseInt(value);
            }
            count++;
            System.out.println("你已經訪問了"+count+"次");
            if(count>3){
                System.out.println("你已經訪問三次,請購買正版");
            }
            //更改訪問的次數
            proterties.setProperty("count", count+"");
            proterties.store(new FileOutputStream("F:\\count.properties"), "count的記錄");
        }
}

 七、常見錯誤

出現這種錯誤,有可能文件地址配置錯誤。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM