java.util.Properties类

前端之家收集整理的这篇文章主要介绍了java.util.Properties类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

功能:读取项目中配置文件  or 为项目中的配置文件填充内容。实质,就是对properties这类配置文件的映射。这类配置文件支持类型包括2类:.properties文件和xml文件类型。

代码都有一个公认的前提:配置文件我放在/Users/cxh/IdeaProjects/JavaBaseTest/src/bin文件夹下;

代码放在/Users/cxh/IdeaProjects/JavaBaseTest/src文件夹下;

配置文件

文件中手动写入代码

代码:

/**

  • Created by cxh on 17/07/21.
    */
    public class Main {
    public static void main(String[] args) throws Exception {
    Properties prop=new Properties();
    FileInputStream fis=new FileInputStream("/Users/cxh/IdeaProjects/JavaBaseTest/src/bin/sample.properties");
    prop.load(fis);
    prop.list(System.out);
    System.out.println();
    System.out.println("The property is : "+prop.getProperty("id"));
    }
    }

测试结果:

The  property is : cxh

Process finished with exit code 0

代码向未创建的新文件printStream

/**

  • Created by cxh on 17/07/21.
    */
    public class Main {
    public static void main(String[] args) {
    Properties p=new Properties();
    p.setProperty("username","cxh1005");
    p.setProperty("sex","女");
    p.setProperty("schoolNum","201609080");
    try{
    PrintStream fw=new PrintStream("/Users/cxh/IdeaProjects/JavaBaseTest/src/bin/printStream.properties");
    p.list(fw);//将内存中内容写入到fw的目录文件
    }catch (IOException e){
    e.printStackTrace();
    }
    }
    }

结果:

文件夹下生成文件:printStream.properties,里面包含内容

那,我们会发现,生产文件中的内容顺序和我们设定的不一样。因为Properties类实现类map接口,它是用key-value存储数据的,数据也是没有顺序保证的。

文件

/**

  • Created by cxh on 17/07/21.
    */
    public class Main {
    public static void main(String[] args) {
    Properties p=new Properties();
    p.setProperty("IP","127.0.0.1");
    p.setProperty("Mac","98:73:41:ac:0f:c2");
    try{
    PrintStream ps=new PrintStream(new File("/Users/cxh/IdeaProjects/JavaBaseTest/src/bin/printStreams.xml"));
    p.storeToXML(ps,"testPrintToXMLFile");
    }catch(IOException e){
    e.printStackTrace();
    }
    }
    }

测试结果:

生成文件:printStream.xml文件内容如下:



testPrintToXMLFile



3.2、读取.xml文件里面的内容

生成文件readSteam.xml文件,然后写入内容



    testPrintReadFromXMLFile
    
    

3.2.2、读取<span style="font-size:14px;">readSteam.xml文件里面的内容

/**

  • Created by cxh on 17/07/21.
    */
    public class Main {
    public static void main(String[] args) throws Exception{
    Properties p=new Properties();
    FileInputStream fis=new FileInputStream("/Users/cxh/IdeaProjects/JavaBaseTest/src/bin/readStream.xml");
    p.loadFromXML(fis);
    p.list(System.out);
    System.out.println(); //空行
    System.out.println("the Mac property is :"+p.getProperty("Mac"));
    }
    }

输出内容

the Mac property is :98:73:41:ac:0f:c2

Process finished with exit code 0

猜你在找的Java相关文章