java.util.properties工具类操作properties配置文件

properties基本功能

  • 读取properties配置文件
  • 备份properties配置文件
    • 备份到properties文件
    • 备份到xml文件
  • 编辑properties文件和对于的xml文件
    • 删除某行
    • 修改某行
    • 新增一行

代码示例


package temp.test;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Properties;

public class TestProperties
{

    public static void main(String[] args)
    {
        String strPath = "TestFile/ttt.properties";
        try
        {
            //读取properties文件
            InputStream ioInput = new FileInputStream(strPath);
            Properties oTempProperties = new Properties();
            oTempProperties.load(ioInput);
            for (Object key : oTempProperties.keySet())
            {
                System.out.println(key + "= " + oTempProperties.get(key));
            }
            //备份properties文件 (1.properties文件  2.备份到xml文件)
            String strBakPath = "TestFile/ttt2.properties";
            String strBakPath2 = "TestFile/ttt.xml";
            OutputStream ioOutPut = new FileOutputStream(strBakPath);
            OutputStream ioOutPut2 = new FileOutputStream(strBakPath2);
            oTempProperties.store(ioOutPut, "备份properties");
            oTempProperties.storeToXML(ioOutPut2, "备份properties");

            ioOutPut.close();
            ioOutPut2.close();
            //修改properties配置文件
            OutputStream ioOutPutStream = new FileOutputStream(strPath);
            oTempProperties.setProperty("a", "aaaachaged");
            oTempProperties.remove("b");
            oTempProperties.setProperty("c", "cccccchanged");
            oTempProperties.store(ioOutPutStream, "修改后的properties");
            ioOutPutStream.close();
            ioInput.close();
            //修改xml文件
            InputStream ioInputXml = new FileInputStream(strBakPath2);
            oTempProperties.loadFromXML(ioInputXml);
            oTempProperties.setProperty("a", "aaaachanged");
            oTempProperties.remove("b");
            oTempProperties.setProperty("c", "ccccchanged");
            OutputStream ioOutPutXml = new FileOutputStream(strBakPath2);
            oTempProperties.storeToXML(ioOutPutXml, "修改后的xml");
            ioInputXml.close();
            ioOutPutXml.close();
        }
        catch (FileNotFoundException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        catch (IOException e)
        {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

}

你可能感兴趣的:(JAVA)