properties 配置文件中值换行的问题

在使用properties配置文件的时候我们经常碰到如下两个问题

1:当a=b中的b值内容特别长的时候为了阅读方便我们手动换行,但如果我们直接回车那么后面的数据就会丢失。那如何解决呢?

例如:

a=aaaaaaaaasdfasdfasdfasdfasdfadfasdfaf

我们如果想分两行卸载配置文件中应该如下写法

a=aaaaaaaaas\

dfasdfasdfasdfasdfadfasdfaf

 

2:当a=b中的b值内容特别长并且里面要分多行的话。

例如我们想打印出的值如下

aaaaaaaaaa

bbbbbbbb

cccccc

cccccc

那么我们配置文件中应该如下编写

a=aaaaaaaaaa\nbbbbbbbb\ncccccc\ncccccc


Java读取Properties文件时碰到两问题:

 资源文件中的key对应的value过长时,书写不方便,需要换行,若直接回车则回车后的内容被忽略

资源文件中的key对应的value需要换行显示时,若直接回车,则同样丢掉回车后的部分

    要 解决这两个问题其实不是很难,只是大家对properties文件的熟悉程度不太一样。我就是因为不熟悉以前都是一位换行就可以了,但是这是不行的。如果 是用回车直接换行,则properties文件会自动以某个特殊字符作为分割符将这行value分割为key/value的形式。

 

1
2
3
4
5
6
7
8
9
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


测试源码如下:

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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直接获取。

posted @ 2016-12-06 20:33  kabibo  阅读(1347)  评论(0编辑  收藏  举报