JavaがプロパティファイルやXMLファイルを読み書きして中国語の文字化け問題を解決


序文

開発中に構成ファイルを使用する必要があることがよくあります。構成ファイルで変更および構成する必要があるパラメータ値を簡単に設定できます。データベース IP やアカウントなど、ローカル開発環境と運用環境の一部のパラメータが異なる場合があります。パスワードなど、読み込むフォルダのパス、ログバックアップの時間や周期など、そろそろこれらの値を最終変数として直接定義すればいいのではないかという人もいるかもしれません。この欠点は、プロジェクトを実稼働環境にデプロイするときに、Java コードを再調整してから、jar パッケージまたは war パッケージを再生成する必要があり、その定義を構成ファイルで直接開いて変更できることです。設定ファイル内のこれらのパラメータは、その後の変更に非常に便利です。
Javaでよく使われる設定ファイルはプロパティ、xml、txtですが、この記事ではこれら3つの設定ファイルの読み書き方法を紹介します。


1. プロパティファイル

1.1プロパティ形式の概要

プロパティファイルはテキストファイルであり、プロパティの設定情報が「key=value」の形式で記述されます。
ここに画像の説明を挿入
上記のクラス構成図からもわかるように、Hashtableを継承し、
Mapインタフェースのプロパティを実装しており、キー値の前後のスペースは解析時に無視されます。
注: 先頭に # を追加します
ここに画像の説明を挿入

1.2 プロジェクトリソース/テンプレート配下のプロパティを読み込み、中国語文字化けに対処する

プロパティファイルを読み込む際、読み込んだ値に中国語が含まれている場合は文字化けが発生するため、再度処理が必要になることに注意してください。
ここに画像の説明を挿入
プロパティ ファイルはプロジェクト リソース/テンプレートの下に配置され、
コードは次のとおりです。

    //读取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 ローカルプロパティの読み込みと中国語文字化けへの対処

プロパティ ファイルがローカルにある場合は、次のように読み取ることができます。
コードは次のとおりです。

    //读取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 プロパティファイルを変更する

    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ファイル

2.1xml ファイル形式

ML は Extensible Markup Language (EXtensible Markup Language) の略で、HTML によく似たマークアップ言語です。
XML では、独自のタグを拡張したり作成したりできます。XML には事前定義されたタグはなく、XML では作成者が独自のタグと文書構造を定義または設計できます。基本構造: XML 文書の接尾辞名。xml XML の最初の行ドキュメント
定義する必要があります。宣言 プロジェクトでよく見られる XML ファイルは pom.xml です。これは誰もがよく知っているはずです。mybatis で使用される mybatis.xml もあります



<?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 XMLファイルの読み込み

コードは次のとおりです(例)。

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 XMLファイルの書き込み

コードは次のとおりです(例)。

//写资源文件到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();
        }
    }

おすすめ

転載: blog.csdn.net/sunzixiao/article/details/132076095