Java reads and writes properties files and xml files to solve the problem of Chinese garbled characters


foreword

We often need to use configuration files during development. We can easily set the parameter values ​​that need to be modified and configured in the configuration file. Sometimes some parameters in our local development and production environments are different, such as database IP and account number. Password, etc., the path of the folder to be read, the time and cycle of log backup, etc., some people may say that it will be possible to directly define these values ​​​​as final variables soon? The disadvantage of this is that when we deploy the project to the production environment, we have to readjust the Java code, and then regenerate the jar package or war package, and the definition can be directly opened in the configuration file for modification. We set these parameters in the configuration file It is very convenient for subsequent modification.
The commonly used configuration files in java are properties, xml and txt. This article will introduce the reading and writing methods of these three configuration files.


1. Properties file

1.1properties format introduction

The properties file is a text file, and the configuration information of a property is written in the form of "key=value".
insert image description here
As can be seen from the above class structure diagram, it inherits Hashtable and implements
the properties of the Map interface properties. The spaces before and after the key value are ignored during parsing.
Note: add # in front
insert image description here

1.2 Read the properties under project resource/templates and deal with Chinese garbled characters

When reading the properties file, it should be noted that if the read value contains Chinese, there will be garbled characters, which needs to be processed again.
insert image description here
The properties file is placed under the project resource/templates and
the code is as follows:

    //读取properties资源文件
    public static String getProperties() {
    
    
        Properties properties = new Properties();
        try {
    
    
            InputStream resourceAsStream = SysSetParaEditController.class.getClassLoader().getResourceAsStream("getGKCX.properties");
            properties.load(resourceAsStream);
            String head = properties.getProperty("head");
            String content = properties.getProperty("content");
            String body = properties.getProperty("body");
            String function = properties.getProperty("function");
            String arg = properties.getProperty("arg");
            String functionend = properties.getProperty("functionend");
            String bodyend = properties.getProperty("bodyend");
            String contentend = properties.getProperty("contentend");
            System.out.println(head + "-->" + head);
            System.out.println(content + "-->" + content);
            System.out.println(body + "-->" + body);
            System.out.println(function + "-->" + function);
            System.out.println(arg + "-->" + arg);
            System.out.println(functionend + "-->" + functionend);
            System.out.println(bodyend + "-->" + bodyend);
            System.out.println(contentend + "-->" + contentend);
            resourceAsStream.close(); //关闭流
        }
        catch (IOException e) {
    
    
            e.printStackTrace();
        }
        //处理中文乱码
        String imgFolder = properties.getProperty("imgFolder");
        try {
    
    
            imgFolder = new String(imgFolder.getBytes("ISO-8859-1"), "GBK"); // 处理中文乱码
        }
        catch (UnsupportedEncodingException e) {
    
    
            e.printStackTrace();
        }
        System.out.println(imgFolder);
        return imgFolder;
    }

1.3 Read local properties and deal with Chinese garbled characters

If the properties file is local, it can be read like this:
the code is as follows:

    //读取properties资源文件
    public static String getProperties() {
    
    
         Properties pro = new Properties();
        int maxTotal = 0;
        int maxIdel = 0;
        String host = null;
        int port = 0;
        try {
    
    
            pro.load(new FileReader("D:\\sun\\getGKCX.properties"));
            String imgFolder = properties.getProperty("imgFolder");
            imgFolder = new String(imgFolder.getBytes("ISO-8859-1"), "GBK"); // 处理中文乱码
        } catch (IOException e) {
    
    
            e.printStackTrace();
        }
        System.out.println(imgFolder);
        return imgFolder;
    }

1.4 Modify the properties file

    public static void writePropertiesFile(String filename)
    {
    
    
        Properties properties = new Properties();
        try{
    
    
        	//方法一:使用FileWriter 
            properties.setProperty("imgFolder", "D:\\sun");
            //创建字节输出流/字符输出流,构造方法中绑定要输出的目的地
            FileWriter fw=new FileWriter("D://a.txt");
            //使用Properties集合中的方法store,把集合中的临时数据,持久写入到硬盘中
            properties.store(fw, "save data");
            //释放资源
            fw.close();
            
            //方法二:使用OutputStream 
            OutputStream outputStream = new FileOutputStream(filename);
            properties.setProperty("imgFolder", "D:\\sun\\img");
            properties.store(outputStream, "author: sun");
            outputStream.close();
        }
        catch (IOException e)
        {
    
    
            e.printStackTrace();
        }
    }

2. XML file

2.1xml file format

ML stands for Extensible Markup Language (EXtensible Markup Language), which is a markup language very similar to HTML.
In XML, you can expand and invent your own tags. XML has no predefined tags, and XML allows creators to define or design their own tags and document structure. Basic structure: The suffix name of the XML document.xml The first line of XML must
define
the
document Declaration
The xml file that is often seen in the project is pom.xml, I believe everyone must be familiar with this!
There is also mybatis.xml used by mybatis

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <!--<environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://127.0.0.1/table?useUnicode=true&amp;characterEncoding=utf-8&amp;allowMultiQueries=true&amp;useSSL=false&amp;severTimezone=GMT%2B8"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>-->
    <mappers>
         <mapper resource="com/sun/server/mapper/xml/TScdLogMapper.xml"/>
         <mapper resource="com/sun/server/mapper/xml/TScdOperateMapper.xml"/>
         <mapper resource="com/sun/server/mapper/xml/TScdOperatePartsMapper.xml"/>
         <mapper resource="com/sun/server/mapper/xml/TSysParainfoMapper.xml"/>
    </mappers>
</configuration>

2.2 read xml file

The code is as follows (example):

public static void readPropertiesFileFromXML(String filename)
    {
    
    
        Properties properties = new Properties();
        try
        {
    
    
            InputStream inputStream = new FileInputStream(filename);
            properties.loadFromXML(inputStream);
            inputStream.close();
        }
        catch (IOException e)
        {
    
    
            e.printStackTrace();
        }
        String imgFolder = properties.getProperty("imgFolder");; //XML中的中文不用处理乱码,正常显示
    }

2.3 Write xml file

The code is as follows (example):

//写资源文件到XML文件,含中文  
    public static void writePropertiesFileToXML(String filename)
    {
    
    
        Properties properties = new Properties();
        try
        {
    
    
            OutputStream outputStream = new FileOutputStream(filename);
            properties.setProperty("imgFolder", "D:\\sun\\img");
            properties.storeToXML(outputStream, "author: sun");
            outputStream.close();
        }
        catch (IOException e)
        {
    
    
            e.printStackTrace();
        }
    }

Guess you like

Origin blog.csdn.net/sunzixiao/article/details/132076095