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的记录");
        }
}

 七、常见错误

出现这种错误,有可能文件地址配置错误。

原文地址:https://www.cnblogs.com/lyjs/p/4871243.html