解決Java讀取properties檔案的中文問題的新辦法(不使用native2ascii.exe及其他工具)

來源:互聯網
上載者:User

解決Java讀取properties檔案的中文問題的新辦法(不使用native2ascii.exe及其他工具)


原理:轉碼
關鍵代碼:new String(temp.getBytes("ISO-8859-1"), "GBK")
其實很簡單,就是簡單的轉碼,下面給出原始碼(兩個ReadProperties.java和LogSystem.properties)和使用方法:

ReadProperties.java

import java.util.Properties;
import java.io.UnsupportedEncodingException;
import java.io.FileInputStream;
import java.io.*;

public class ReadProperties {
    private static Properties props = new Properties();
    private static FileInputStream fis;
    private static String propertiesName = "LogSystem.properties"; //需要讀取的properties檔案名稱,預設目前的目錄下

    private static void InitializationProperties() {
        try {
            fis = new FileInputStream(propertiesName);
            props.load(fis);
            fis.close();
        } catch (FileNotFoundException ex) {
            System.out.println("logsystem.tools.ReadProperties :系統找不到檔案->" +
                               propertiesName);
        } catch (IOException ex) {
            ex.printStackTrace();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException ex1) {
                    ex1.printStackTrace();
                }
            }
        }
    }

    /**
     * 根據配置項擷取配置值
     * 可以相容GBK編碼,支援中文
     * @param key String        -- 配置項
     * @return  String          -- 配置值
     */
    public static String getPropertyByKey(String key) {
        InitializationProperties();
        String temp = props.getProperty(key);
        String sp = "";
        if (temp != null) {
            try {
                sp = new String(temp.getBytes("ISO-8859-1"), "GBK");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        props.clear();
        return sp;
    }

    public static void main(String[] args) {

        System.out.println(ReadProperties.getPropertyByKey("clientlogfilename"));//使用方法,很簡單吧?
    }
}

 

clientlogfilename=我不是一個人

控制台列印:

我不是一個人

希望對大家能有所協助! 


 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.