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直接获取。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章