properties 文件 屬性值過長換行如理 測試讀取配置文件

Java讀取Properties文件時碰到兩問題:

1. 資源文件中的key對應的value過長時,書寫不方便,需要換行,若直接回車則回車後的內容被忽略

2. 資源文件中的key對應的value需要換行顯示時,若直接回車,則同樣丟掉回車後的部分

    要解決這兩個問題其實不是很難,只是大家對properties文件的熟悉程度不太一樣。我就是因爲不熟悉以前都是一位換行就可以了,但是這是不行的。如果是用回車直接換行,則properties文件會自動以某個特殊字符作爲分割符將這行value分割爲key/value的形式。

    解決這個問題可以用"\"這個符號加以分割,之後"\"之後可以用回車換行。下一行開始之前可以添加很多空格加以格式化,而且可以多行如下圖。而且

key1=Where did you take the picture?\
     It's so beautiful!\
     It's so beautiful!\
     asdfasdfasd\
     asfasdfsdfsadf\
     asdfsadfsadfsdf\
     asdfsdfasdfsadf\
     asdfsadfsdf
key2=Spring\nHibernate\nIbatis\nVelocity\nJava/nStruts

package com.icbc.ctie.build;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class PropertiesTest {
	public static void main(String[] args){
		Properties properties = new Properties();  
        try  
        {  
           InputStream inputStream = PropertiesTest.class.getClassLoader().getResourceAsStream("test.properties");  
        /*   File property=new File("test.properties");
           FileInputStream inputStream=new FileInputStream(property);*/
        	properties.load(inputStream);  
            inputStream.close(); //關閉流  
        }  
        catch (IOException e)  
        {  
            e.printStackTrace();  
        }  
        String key1 = properties.getProperty("key1");  
        String key2 = properties.getProperty("key2");  
        System.out.println(key1);  
        System.out.println(key2);  
	}
}

上述代碼如果用getResourceAsStream 方法就必須將test.properties文件放到src下或者添加至構建路徑中。否則就是用File直接獲取。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章