Java读取资源文件时内容过长与换行的处理


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

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

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

针对上述问题找到如下解决办法:

1. 内容过长需要换行时拼接个/斜杠,这样/后的内容后正常显示

2.若内容本身需要换行时则用/n代替回车

  1. package apistudy;  
  2.   
  3. import java.io.IOException;  
  4. import java.io.InputStream;  
  5. import java.util.Properties;  
  6.   
  7. public class PropertiesTest2  
  8. {  
  9.   
  10.     public static void main(String[] args)  
  11.     {  
  12.         Properties properties = new Properties();  
  13.         try  
  14.         {  
  15.             InputStream inputStream = PropertiesTest2.class.getClassLoader().getResourceAsStream("test.properties");  
  16.             properties.load(inputStream);  
  17.             inputStream.close(); //关闭流   
  18.         }  
  19.         catch (IOException e)  
  20.         {  
  21.             e.printStackTrace();  
  22.         }  
  23.         String key1 = properties.getProperty("key1");  
  24.         String key2 = properties.getProperty("key2");  
  25.         System.out.println(key1);  
  26.         System.out.println(key2);  
  27.           
  28.     }  
  29.   
  30. }  

输出结果:

Where did you take the picture? It's so beautiful!
Spring
Hibernate
Ibatis
Velocity
Java
Struts

附:test.properties中的内容

key1=Where did you take the picture? /
It's so beautiful!
key2=Spring/nHibernate/nIbatis/nVelocity/nJava/nStruts

相关内容