一、在 properties 文件中 定义{ } 会出错
使用MessageFormat.applyPattern时一直抛出异常:
java.lang.IllegalArgumentException: can't parse argument number margin-top: 0px; margin-right: 0px; margin-bottom: 0px; margin-left: 0px;
经过检查是properties文件中的“{”引起的 ,因为这一段是css的style,但是applyPattern是将这个“{”当成占位符处理了 ,\u007B也试过了,不好使,没办法只能查看java源代码,这个方法的代码如下:
public void applyPattern(String pattern) {
StringBuffer[] segments = new StringBuffer[4];
for (int i = 0; i < segments.length; ++i) {
segments[i] = new StringBuffer();
}
int part = 0;
int formatNumber = 0;
boolean inQuote = false;
int braceStack = 0;
maxOffset = -1;
for (int i = 0; i < pattern.length(); ++i) {
char ch = pattern.charAt(i);
if (part == 0) {
if (ch == '\'') {
if (i + 1 < pattern.length()
&& pattern.charAt(i+1) == '\'') {
segments[part].append(ch); // handle doubles
++i;
} else {
inQuote = !inQuote;
}
} else if (ch == '{' && !inQuote) {
part = 1;
} else {
segments[part].append(ch);
}
} else if (inQuote) { // just copy quotes in parts
segments[part].append(ch);
if (ch == '\'') {
inQuote = false;
}
} else {
switch (ch) {
case ',':
if (part < 3)
part += 1;
else
segments[part].append(ch);
break;
case '{':
++braceStack;
segments[part].append(ch);
break;
case '}':
if (braceStack == 0) {
part = 0;
makeFormat(i, formatNumber, segments);
formatNumber++;
} else {
--braceStack;
segments[part].append(ch);
}
break;
case '\'':
inQuote = true;
// fall through, so we keep quotes in other parts
default:
segments[part].append(ch);
break;
}
}
}
if (braceStack == 0 && part != 0) {
maxOffset = -1;
throw new IllegalArgumentException("Unmatched braces in the pattern.");
}
this.pattern = segments[0].toString();
}
发现这一段:
if (ch == '\'') {
if (i + 1 < pattern.length()
&& pattern.charAt(i+1) == '\'') {
segments[part].append(ch); // handle doubles
++i;
} else {
inQuote = !inQuote;
}
}
转移符竟然是“ \' ”,想用单引号就写成“ \'\' ” ,想用 { 就写成 “ \'\{ ”
二、 properties 文件内 换行、输出时 换行
Java读取资源文件时内容过长与换行的处理
Java读取Properties文件时碰到两问题
1.
资源文件中的key对应的value过长时,书写不方便,需要换行,若直接回车则回车后的内容被忽略
2.
资源文件中的key对应的value需要换行显示时,若直接回车,则同样丢掉回车后的部分
针对上述问题找到如下解决办法:
1.
内容过长需要换行时拼接个\斜杠,这样\后的内容后正常显示
2.
若内容本身需要换行时则用\n代替回车
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesTest2
{
public static void main(String[] args)
{
Properties properties = new Properties();
try
{
InputStream inputStream = PropertiesTest2.class.getClassLoader().getResourceAsStream("test.properties");
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);
}
}
输出结果:
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