美文网首页
Properties 类的用法

Properties 类的用法

作者: 浅陌_45f3 | 来源:发表于2019-11-04 16:36 被阅读0次

java.uti.properties
项目主要用它来读取配置文件,可以读取以 .properties 结尾的文件或者 xml 文件,主要用 load 、loadFromXML 方法将配置文件映射为 map 文件。用 list 方法可将内容输出,既可以输出到控制台也可以输出到文件中。

例1:读取以 .properties 结尾的文件

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropTest{
   public static void main(String[] args) throws IOException{
      File file = new File("D:\\PropTest.properties");
      FileInputStream in = new FileInputStream(file);
      
      Properties p = new Properties();
      //将配置文件通过 load 方法映射成 map
      p.load(in);
      //输出文件内容,也可以输出到文件中
      p.list(System.out);
   }
}

properties 文件内容如下:

website = https://cn.bing.com/
author = root
date = 20191104

输出结果如下:

-- listing properties --
website=https://cn.bing.com/
date=20191104
author=root

例2:读取 xml 文件

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;

public class PropTest{
   public static void main(String[] args) throws IOException{
      File file = new File("D:\\XmlTest.xml");
      FileInputStream in = new FileInputStream(file);
      
      Properties p = new Properties();
      //将配置文件通过 loadFromXML 方法映射成 map
      p.loadFromXML(in);
      //输出文件内容,也可以输出到文件中
      p.list(System.out);
   }
}

xml 文件内容:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<entry key="website">bing.com</entry>
<entry key="author">root</entry>
</properties>

输出结果:

-- listing properties --
website=bing.com
author=root

例3:将内存写入 properties 配置文件

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Properties;
public class WriteProp throws FileNotFoundException{
    public static void main(String[] args){
        Properties prop = new Properties();
        prop.setProperty("id", "1");
        prop.setProperty("name", "root");

        PrintStream in = new PrintStream(new File("D:\\writeprop.properties"));
        prop.list(in);
    }
}

输出结果:

-- listing properties --
name=root
id=1

例4:将内存写入 xml 配置文件

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;
import java.util.Properties;
public class WriteProp  throws IOException{
    public static void main(String[] args){
        Properties prop = new Properties();
        prop.setProperty("id", "2");
        prop.setProperty("name", "root2");

        PrintStream in = new PrintStream(new File("D:\\writexml.xml"));
        prop.storeToXML(in, "writexml");
    }
}

输出结果:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>writexml</comment>
<entry key="name">root2</entry>
<entry key="id">2</entry>
</properties>

相关文章

网友评论

      本文标题:Properties 类的用法

      本文链接:https://www.haomeiwen.com/subject/rysdbctx.html